diff --git a/.gitignore b/.gitignore index c6aa4d053..e24fe0bbb 100644 --- a/.gitignore +++ b/.gitignore @@ -9,11 +9,19 @@ tools/eclipse/plugins/org.scribble.*/bin/ *~ *.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/ @@ -33,26 +41,36 @@ scribble-demos/scrib/smtp/src/smtp/Smtp/ scribble-demos/scrib/travel/src/travel/Travel/ scribble-demos/scrib/tutorial/src/tutorial/adder/Adder/ -#scribble-core/src/test/scrib - -scribble-core/src/test/scrib/exercise/calculator/EProtocol/ -scribble-core/src/test/scrib/exercise/voting/EProtocol/ - -scribble-core/src/test/scrib/demo/fase17/travel/TravelAgent/ -scribble-core/src/test/scrib/demo/fase17/travel2/TravelAgent2/ - -scribble-core/src/test/scrib/scratch/scratch1/ -scribble-core/src/test/scrib/scratch/scratch2/ -scribble-core/src/test/scrib/test/foo/Foo/ -scribble-core/src/test/scrib/test/test1/ -scribble-core/src/test/scrib/test/test2/ -scribble-core/src/test/scrib/test/test3/ -scribble-core/src/test/scrib/test/test4/ -scribble-core/src/test/scrib/test/test5/ -scribble-core/src/test/scrib/test/test6/ -scribble-core/src/test/scrib/test/test7/ -scribble-core/src/test/scrib/test/test8/ -scribble-core/src/test/scrib/test/test9/ + +## +#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 diff --git a/README.md b/README.md index 7ee299c2b..408b44a3a 100644 --- a/README.md +++ b/README.md @@ -2,17 +2,19 @@ # Java Tooling for Scribble -This project provides Java tooling/libraries for the Scribble multi-party protocol definition language. +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: +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: +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 @@ -20,21 +22,20 @@ The distribution will be available from the folder _scribble-dist/target_. The c ## 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, e.g., Test.scr. +> Check well-formedness of global protocols in module Test.scr. ./scribblec.sh Test.scr -Notes: -- Use the -oldwf command line flag to use the simpler syntactic protocol - well-formedness from the previous version of Scribble. -- Use the -V command line flag to obtain full traces for errors according - to the new protocol validation (and other details). - +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 @@ -52,6 +53,8 @@ Notes: ./scribblec.sh -d . Test.scr -api Proto C +Note: omitting the -d argument will print the output to stdout. + ## Examples: @@ -64,8 +67,8 @@ 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. +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) @@ -93,7 +96,7 @@ Or try (from Nick Ng): Bugs and issues can be reported via the github Issues facility. -Or email rhu1234 [at] doc.ic.ac.uk excluding the 1234. +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 @@ -102,3 +105,4 @@ Or email rhu1234 [at] doc.ic.ac.uk excluding the 1234. [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/pom.xml b/pom.xml index f0181a08d..188655f30 100644 --- a/pom.xml +++ b/pom.xml @@ -1,384 +1,418 @@ + + + 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} + - - 4.0.0 - org.scribble - parent - 0.4.4-SNAPSHOT - pom - scribble-java - http://www.scribble.org - - Scribble - + + org.antlr + antlr-runtime + ${antlr.version} + + + junit + junit + ${junit.version} + + + commons-io + commons-io + ${version.commons-io} + + + + - - 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 - + + scribble-core + scribble-runtime + scribble-ast + scribble-parser + scribble-codegen + scribble-main + scribble-cli + scribble-test + scribble-dist + scribble-demos + - - - Apache 2 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - Apache License V2 - - + + 3.4 + 4.13.1 + + + 2.7 - - - Gary Brown - objectiser - gary.pi4tech@gmail.com - Scribble.org - - Developer - - +0 - - + + 1.8 + 1.8 + true - 2008 + + 2.5.3 + 3.2.1 + + 2.9 + 0.3.4 + 0.1.0 + - - Scribble - http://www.scribble.org - + UTF-8 + - - 3.4 - 1.2.14 - 1.9.9 - 4.11 - 2.4 + scribble-java + Scribble + http://www.scribble.org + 2008 - - 1.8 - 1.8 - true + + + Apache 2 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + Apache License V2 + + - 2.8.2 - 2.5.3 - 3.0.1 - 2.10.4 - 0.3.4 - 0.1.0 - + + Scribble + http://www.scribble.org + - - scribble-core - scribble-parser - scribble-cli - scribble-codegen - scribble-runtime - scribble-test - scribble-dist - scribble-demos - + + + 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.scribble - scribble-core - ${project.version} - - - org.scribble - scribble-parser - ${project.version} - - - org.scribble - scribble-cli - ${project.version} - - - org.scribble - scribble-runtime - ${project.version} - - - org.scribble - scribble-codegen - ${project.version} - - - - org.scribble - scribble-test - ${project.version} - - - org.antlr - antlr-runtime - ${antlr.version} - - - junit - junit - ${junit.version} - + + + + + + + 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 + - - commons-io - commons-io - ${version.commons-io} - - - org.codehaus.jackson - jackson-core-asl - ${jackson.version} - - - org.codehaus.jackson - jackson-mapper-asl - ${jackson.version} - - - log4j - log4j - ${log4j.version} - - - + + + io.takari + maven + ${version.io.takari-maven} + + + - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9 - - - 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 - + + + + 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 + + + - - - io.takari - maven - ${version.io.takari-maven} - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.2 - - - - org.apache.maven.plugins - 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-checkstyle-plugin - 2.6 - - checkstyle/checkstyle.xml - false - checkstyle/suppressions.xml - false - - - - - org.scribble - build - ${project.version} - - - - - check-style - site - - checkstyle - - - - - - 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 - **/Scribble-0.3.original - **/IGNORE - bin/*.sh - scribblec.sh - **/*.swp - - 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 + + + - - - - org.apache.maven.plugins - maven-surefire-report-plugin - - - - - - bintray - https://api.bintray.com/maven/scribble/maven/scribble-java/;publish=1 - - - jfrog-snapshots - http://oss.jfrog.org/artifactory/oss-snapshot-local - - + + 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 - - - - - - - + + + + + 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/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-core/src/main/java/org/scribble/ast/DoArgNode.java b/scribble-ast/src/main/java/org/scribble/ast/DoArgNode.java similarity index 100% rename from scribble-core/src/main/java/org/scribble/ast/DoArgNode.java rename to scribble-ast/src/main/java/org/scribble/ast/DoArgNode.java 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-core/src/main/java/org/scribble/ast/ModuleMember.java b/scribble-ast/src/main/java/org/scribble/ast/ModuleMember.java similarity index 78% rename from scribble-core/src/main/java/org/scribble/ast/ModuleMember.java rename to scribble-ast/src/main/java/org/scribble/ast/ModuleMember.java index 4be80e0bf..c0ce26cab 100644 --- a/scribble-core/src/main/java/org/scribble/ast/ModuleMember.java +++ b/scribble-ast/src/main/java/org/scribble/ast/ModuleMember.java @@ -13,11 +13,12 @@ */ package org.scribble.ast; -import org.scribble.type.kind.ModuleMemberKind; -import org.scribble.type.name.MemberName; +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) + 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-core/src/main/java/org/scribble/ast/NonRoleArgNode.java b/scribble-ast/src/main/java/org/scribble/ast/NonRoleArgNode.java similarity index 82% rename from scribble-core/src/main/java/org/scribble/ast/NonRoleArgNode.java rename to scribble-ast/src/main/java/org/scribble/ast/NonRoleArgNode.java index c4d9c43fe..8a1f0ff4e 100644 --- a/scribble-core/src/main/java/org/scribble/ast/NonRoleArgNode.java +++ b/scribble-ast/src/main/java/org/scribble/ast/NonRoleArgNode.java @@ -13,35 +13,40 @@ */ package org.scribble.ast; -import org.scribble.type.Arg; -import org.scribble.type.kind.NonRoleArgKind; +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 isMessageSigNode() + default boolean isSigLitNode() { return false; } - default boolean isMessageSigNameNode() + default boolean isSigNameNode() { return false; } - default boolean isDataTypeNameNode() + default boolean isDataNameNode() { return false; } - default boolean isParamNode() + default boolean isSigParamNode() + { + return false; + } + + default boolean isDataParamNode() { return false; } - - Arg toArg(); } 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-core/src/main/java/org/scribble/del/DefaultDel.java b/scribble-ast/src/main/java/org/scribble/del/DefaultDel.java similarity index 100% rename from scribble-core/src/main/java/org/scribble/del/DefaultDel.java rename to scribble-ast/src/main/java/org/scribble/del/DefaultDel.java 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-core/src/main/java/org/scribble/del/ImportModuleDel.java b/scribble-ast/src/main/java/org/scribble/del/ImportModuleDel.java similarity index 100% rename from scribble-core/src/main/java/org/scribble/del/ImportModuleDel.java rename to scribble-ast/src/main/java/org/scribble/del/ImportModuleDel.java 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-core/src/main/java/org/scribble/del/NonRoleParamDeclDel.java b/scribble-ast/src/main/java/org/scribble/del/NonRoleParamDeclDel.java similarity index 76% rename from scribble-core/src/main/java/org/scribble/del/NonRoleParamDeclDel.java rename to scribble-ast/src/main/java/org/scribble/del/NonRoleParamDeclDel.java index df710e241..6ff5c68a1 100644 --- a/scribble-core/src/main/java/org/scribble/del/NonRoleParamDeclDel.java +++ b/scribble-ast/src/main/java/org/scribble/del/NonRoleParamDeclDel.java @@ -15,15 +15,16 @@ import org.scribble.ast.NonRoleParamDecl; import org.scribble.ast.ScribNode; -import org.scribble.main.ScribbleException; -import org.scribble.visit.wf.NameDisambiguator; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; public class NonRoleParamDeclDel extends ScribDelBase { @Override - public void enterDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb) throws ScribbleException + public void enterDisambiguation(ScribNode child, NameDisambiguator disamb) + throws ScribException { NonRoleParamDecl pd = (NonRoleParamDecl) child; - disamb.addParameter(pd.getDeclName(), pd.kind); + disamb.addParam(pd.getDeclName(), pd.kind); } } diff --git a/scribble-core/src/main/java/org/scribble/del/NonRoleParamDeclListDel.java b/scribble-ast/src/main/java/org/scribble/del/NonRoleParamDeclListDel.java similarity index 100% rename from scribble-core/src/main/java/org/scribble/del/NonRoleParamDeclListDel.java rename to scribble-ast/src/main/java/org/scribble/del/NonRoleParamDeclListDel.java 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-core/src/main/java/org/scribble/del/RoleDeclListDel.java b/scribble-ast/src/main/java/org/scribble/del/RoleDeclListDel.java similarity index 100% rename from scribble-core/src/main/java/org/scribble/del/RoleDeclListDel.java rename to scribble-ast/src/main/java/org/scribble/del/RoleDeclListDel.java 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-core/src/main/java/org/scribble/del/local/LDisconnectDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LDisconnectDel.java similarity index 77% rename from scribble-core/src/main/java/org/scribble/del/local/LDisconnectDel.java rename to scribble-ast/src/main/java/org/scribble/del/local/LDisconnectDel.java index e3563ff51..1f7236070 100644 --- a/scribble-core/src/main/java/org/scribble/del/local/LDisconnectDel.java +++ b/scribble-ast/src/main/java/org/scribble/del/local/LDisconnectDel.java @@ -13,17 +13,12 @@ */ package org.scribble.del.local; -import org.scribble.ast.ScribNode; -import org.scribble.ast.local.LDisconnect; import org.scribble.del.ConnectionActionDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.Role; -import org.scribble.visit.context.EGraphBuilder; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; -public class LDisconnectDel extends ConnectionActionDel implements LSimpleInteractionNodeDel +public class LDisconnectDel extends ConnectionActionDel + implements LSimpleSessionNodeDel { - @Override + /*@Override public LDisconnect leaveEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder builder, ScribNode visited) throws ScribbleException { LDisconnect ld = (LDisconnect) visited; @@ -36,5 +31,5 @@ public LDisconnect leaveEGraphBuilding(ScribNode parent, ScribNode child, EGraph 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/scribble-cli/pom.xml b/scribble-cli/pom.xml index fcbf96988..a8b6028f1 100644 --- a/scribble-cli/pom.xml +++ b/scribble-cli/pom.xml @@ -1,16 +1,10 @@ 4.0.0 + + scribble-cli jar - scribble-cli - - - org.scribble - parent - 0.4.4-SNAPSHOT - ../pom.xml - @@ -21,10 +15,18 @@ org.scribble scribble-parser + + org.scribble + scribble-ast + org.scribble scribble-codegen + + org.scribble + scribble-main + commons-io @@ -32,4 +34,14 @@ + + org.scribble + parent + 0.5.1-SNAPSHOT + ../pom.xml + + + + scribble-cli + diff --git a/scribble-cli/src/main/java/org/scribble/cli/CLArgFlag.java b/scribble-cli/src/main/java/org/scribble/cli/CLArgFlag.java deleted file mode 100644 index e14cf7ded..000000000 --- a/scribble-cli/src/main/java/org/scribble/cli/CLArgFlag.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 enum CLArgFlag -{ - // Unique flags - JUNIT, // For internal use (JUnit test harness) - MAIN_MOD, - IMPORT_PATH, - VERBOSE, - SCHAN_API_SUBTYPES, - OLD_WF, - NO_LIVENESS, - LTSCONVERT_MIN, // Currently only affects EFSM output (i.e. -fsm..) and API gen -- doesn't affect validation - FAIR, - NO_LOCAL_CHOICE_SUBJECT_CHECK, - NO_ACCEPT_CORRELATION_CHECK, - DOT, - AUT, - NO_VALIDATION, - INLINE_MAIN_MOD, - - // Non-unique flags - PROJECT, - API_OUTPUT, - EFSM, - VALIDATION_EFSM, - UNFAIR_EFSM, - UNFAIR_EFSM_PNG, - EFSM_PNG, - VALIDATION_EFSM_PNG, - SGRAPH, - UNFAIR_SGRAPH, - SGRAPH_PNG, - UNFAIR_SGRAPH_PNG, - API_GEN, - SESS_API_GEN, - SCHAN_API_GEN, -} diff --git a/scribble-cli/src/main/java/org/scribble/cli/CLArgParser.java b/scribble-cli/src/main/java/org/scribble/cli/CLArgParser.java index e14bd49db..fc77b1158 100644 --- a/scribble-cli/src/main/java/org/scribble/cli/CLArgParser.java +++ b/scribble-cli/src/main/java/org/scribble/cli/CLArgParser.java @@ -14,122 +14,70 @@ package org.scribble.cli; import java.io.File; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; +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 { - // Unique flags - public static final String JUNIT_FLAG = "-junit"; // For internal use (JUnit test harness) - public static final String VERBOSE_FLAG = "-V"; - public static final String IMPORT_PATH_FLAG = "-ip"; - public static final String API_OUTPUT_DIR_FLAG = "-d"; - public static final String STATECHAN_SUBTYPES_FLAG = "-subtypes"; - public static final String OLD_WF_FLAG = "-oldwf"; - public static final String NO_LIVENESS_FLAG = "-nolive"; - public static final String LTSCONVERT_MIN_FLAG = "-minlts"; - public static final String FAIR_FLAG = "-fair"; - public static final String NO_LOCAL_CHOICE_SUBJECT_CHECK = "-nolocalchoicecheck"; - public static final String NO_ACCEPT_CORRELATION_CHECK = "-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 EFSM_PNG_FLAG = "-fsmpng"; - public static final String VALIDATION_EFSM_PNG_FLAG = "-vfsmpng"; - public static final String UNFAIR_EFSM_PNG_FLAG = "-ufsmpng"; - 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"; - - private static final Map UNIQUE_FLAGS = new HashMap<>(); - { - CLArgParser.UNIQUE_FLAGS.put(CLArgParser.JUNIT_FLAG, CLArgFlag.JUNIT); - CLArgParser.UNIQUE_FLAGS.put(CLArgParser.VERBOSE_FLAG, CLArgFlag.VERBOSE); - CLArgParser.UNIQUE_FLAGS.put(CLArgParser.IMPORT_PATH_FLAG, CLArgFlag.IMPORT_PATH); - CLArgParser.UNIQUE_FLAGS.put(CLArgParser.API_OUTPUT_DIR_FLAG, CLArgFlag.API_OUTPUT); - CLArgParser.UNIQUE_FLAGS.put(CLArgParser.STATECHAN_SUBTYPES_FLAG, CLArgFlag.SCHAN_API_SUBTYPES); - CLArgParser.UNIQUE_FLAGS.put(CLArgParser.OLD_WF_FLAG, CLArgFlag.OLD_WF); - CLArgParser.UNIQUE_FLAGS.put(CLArgParser.LTSCONVERT_MIN_FLAG, CLArgFlag.LTSCONVERT_MIN); - CLArgParser.UNIQUE_FLAGS.put(CLArgParser.FAIR_FLAG, CLArgFlag.FAIR); - CLArgParser.UNIQUE_FLAGS.put(CLArgParser.NO_LOCAL_CHOICE_SUBJECT_CHECK, CLArgFlag.NO_LOCAL_CHOICE_SUBJECT_CHECK); - CLArgParser.UNIQUE_FLAGS.put(CLArgParser.NO_ACCEPT_CORRELATION_CHECK, CLArgFlag.NO_ACCEPT_CORRELATION_CHECK); - CLArgParser.UNIQUE_FLAGS.put(CLArgParser.DOT_FLAG, CLArgFlag.DOT); - CLArgParser.UNIQUE_FLAGS.put(CLArgParser.AUT_FLAG, CLArgFlag.AUT); - CLArgParser.UNIQUE_FLAGS.put(CLArgParser.NO_VALIDATION_FLAG, CLArgFlag.NO_VALIDATION); - CLArgParser.UNIQUE_FLAGS.put(CLArgParser.INLINE_MAIN_MOD_FLAG, CLArgFlag.INLINE_MAIN_MOD); - } - - private static final Map NON_UNIQUE_FLAGS = new HashMap<>(); - { - CLArgParser.NON_UNIQUE_FLAGS.put(CLArgParser.PROJECT_FLAG, CLArgFlag.PROJECT); - CLArgParser.NON_UNIQUE_FLAGS.put(CLArgParser.EFSM_FLAG, CLArgFlag.EFSM); - CLArgParser.NON_UNIQUE_FLAGS.put(CLArgParser.VALIDATION_EFSM_FLAG, CLArgFlag.VALIDATION_EFSM); - CLArgParser.NON_UNIQUE_FLAGS.put(CLArgParser.UNFAIR_EFSM_FLAG, CLArgFlag.UNFAIR_EFSM); - CLArgParser.NON_UNIQUE_FLAGS.put(CLArgParser.EFSM_PNG_FLAG, CLArgFlag.EFSM_PNG); - CLArgParser.NON_UNIQUE_FLAGS.put(CLArgParser.VALIDATION_EFSM_PNG_FLAG, CLArgFlag.VALIDATION_EFSM_PNG); - CLArgParser.NON_UNIQUE_FLAGS.put(CLArgParser.UNFAIR_EFSM_PNG_FLAG, CLArgFlag.UNFAIR_EFSM_PNG); - CLArgParser.NON_UNIQUE_FLAGS.put(CLArgParser.SGRAPH_FLAG, CLArgFlag.SGRAPH); - CLArgParser.NON_UNIQUE_FLAGS.put(CLArgParser.UNFAIR_SGRAPH_FLAG, CLArgFlag.UNFAIR_SGRAPH); - CLArgParser.NON_UNIQUE_FLAGS.put(CLArgParser.SGRAPH_PNG_FLAG, CLArgFlag.SGRAPH_PNG); - CLArgParser.NON_UNIQUE_FLAGS.put(CLArgParser.UNFAIR_SGRAPH_PNG_FLAG, CLArgFlag.UNFAIR_SGRAPH_PNG); - CLArgParser.NON_UNIQUE_FLAGS.put(CLArgParser.API_GEN_FLAG, CLArgFlag.API_GEN); - CLArgParser.NON_UNIQUE_FLAGS.put(CLArgParser.SESSION_API_GEN_FLAG, CLArgFlag.SESS_API_GEN); - CLArgParser.NON_UNIQUE_FLAGS.put(CLArgParser.STATECHAN_API_GEN_FLAG, CLArgFlag.SCHAN_API_GEN); - } + private final CLFlags flags; + private final String[] raw; // Raw args from main method - private static final Map FLAGS = new HashMap<>(); - { - CLArgParser.FLAGS.putAll(CLArgParser.UNIQUE_FLAGS); - CLArgParser.FLAGS.putAll(CLArgParser.NON_UNIQUE_FLAGS); - } - - protected final String[] args; - - private final Map parsed = new HashMap<>(); + // Flag String constants from CLFlags -> flag arguments (possibly none) + private final List> parsed = new LinkedList<>(); - public CLArgParser(String[] args) + public CLArgParser(CLFlags flags, String[] raw) { - this.args = args; - //parseArgs(); // No: constructors should not invoke overridable methods (subclass constructor not yet called) + this.flags = flags; + this.raw = raw; } - // For overriding pattern -- should be used explicitly on subclasses (cannot call overridden from constructor) - public final void parse() throws CommandLineException + // Return: left = CLFlags String constant, right = flag args (if any) + public List> getParsed() throws CommandLineException { parseArgs(); - } - - public final Map getArgs() throws CommandLineException - { + 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; } - protected boolean isFlag(String arg) - { - return CLArgParser.FLAGS.containsKey(arg); - } - private void parseArgs() throws CommandLineException { - for (int i = 0; i < this.args.length; i++) + for (int i = 0; i < this.raw.length; ) // Parse args in order { - String arg = this.args[i]; - if (isFlag(arg)) + String arg = this.raw[i]; + if (this.flags.explicit.containsKey(arg)) { - i = this.parseFlag(i); + 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 { @@ -137,281 +85,71 @@ private void parseArgs() throws CommandLineException { if (arg.startsWith("-")) { - throw new CommandLineException("Unknown flag or bad main module arg: " + arg); + throw new CommandLineException( + "Unknown flag or bad main module arg: " + arg); } - // May actually be the second bad argument -- we didn't validate the value of the main arg - throw new CommandLineException("Bad/multiple 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); } - parseMain(i); + i = parseMain(i); } } } - private boolean isMainModuleParsed() - { - return this.parsed.containsKey(CLArgFlag.MAIN_MOD) || this.parsed.containsKey(CLArgFlag.INLINE_MAIN_MOD); - } - - // Pre: i is the index of the current flag to parse - // Post: i is the index of the last argument parsed -- parseArgs does the index increment to the next current flag - // Currently allows repeat flag decls: next overrides previous + // 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 flag = this.args[i]; - switch (flag) + String lab = this.raw[i]; + if (this.flags.explicit.get(lab).unique) { - // Unique flags - - // "Special" args -- not handled via this.parsed - case CLArgParser.IMPORT_PATH_FLAG: - { - return parseImportPath(i); - } - case CLArgParser.INLINE_MAIN_MOD_FLAG: - { - if (isMainModuleParsed()) - { - throw new CommandLineException("Multiple main modules given."); - } - return parseInlineMainModule(i); - } - // No-value args -- just boolean flags - case CLArgParser.JUNIT_FLAG: - case CLArgParser.VERBOSE_FLAG: - case CLArgParser.STATECHAN_SUBTYPES_FLAG: - case CLArgParser.OLD_WF_FLAG: - case CLArgParser.NO_LIVENESS_FLAG: - case CLArgParser.LTSCONVERT_MIN_FLAG: - case CLArgParser.FAIR_FLAG: - case CLArgParser.NO_LOCAL_CHOICE_SUBJECT_CHECK: - case CLArgParser.NO_ACCEPT_CORRELATION_CHECK: - case CLArgParser.NO_VALIDATION_FLAG: - { - checkAndAddNoArgUniqueFlag(flag); - return i; - } - // Args with one or more values to go in this.parsed - case CLArgParser.API_OUTPUT_DIR_FLAG: - { - return parseOutput(i); - } - case CLArgParser.DOT_FLAG: - { - if (this.parsed.containsKey(CLArgParser.UNIQUE_FLAGS.get(AUT_FLAG))) - { - throw new CommandLineException("Incompatible flags: " + DOT_FLAG + " and " + AUT_FLAG); - } - checkAndAddNoArgUniqueFlag(flag); - return i; - } - case CLArgParser.AUT_FLAG: - { - if (this.parsed.containsKey(CLArgParser.UNIQUE_FLAGS.get(DOT_FLAG))) - { - throw new CommandLineException("Incompatible flags: " + DOT_FLAG + " and " + AUT_FLAG); - } - checkAndAddNoArgUniqueFlag(flag); - return i; - } - - - // Non-unique flags - - case CLArgParser.PROJECT_FLAG: - { - return parseProject(i); - } - case CLArgParser.EFSM_FLAG: - case CLArgParser.VALIDATION_EFSM_FLAG: - case CLArgParser.UNFAIR_EFSM_FLAG: - case CLArgParser.API_GEN_FLAG: - case CLArgParser.STATECHAN_API_GEN_FLAG: - { - return parseProtoAndRoleArgs(flag, i); - } - case CLArgParser.EFSM_PNG_FLAG: - case CLArgParser.VALIDATION_EFSM_PNG_FLAG: - case CLArgParser.UNFAIR_EFSM_PNG_FLAG: - { - return parseProtoRoleAndFileArgs(flag, i); - } - case CLArgParser.SGRAPH_FLAG: - case CLArgParser.UNFAIR_SGRAPH_FLAG: - case CLArgParser.SESSION_API_GEN_FLAG: - { - return parseProtoArg(flag, i); - } - case CLArgParser.SGRAPH_PNG_FLAG: - case CLArgParser.UNFAIR_SGRAPH_PNG_FLAG: - { - return parseProtoAndFileArgs(flag, i); - } - - - default: + if (getParsedKeys().contains(lab)) { - throw new RuntimeException("[TODO] Unknown flag: " + flag); + throw new CommandLineException("duplicate: " + lab); } } - } - - private void checkAndAddNoArgUniqueFlag(String flag) throws CommandLineException - { - checkAndAddUniqueFlag(flag, new String[0]); - } - - private void checkAndAddUniqueFlag(String flag, String[] args) throws CommandLineException - { - CLArgFlag argFlag = CLArgParser.UNIQUE_FLAGS.get(flag); - if (this.parsed.containsKey(argFlag)) - { - throw new CommandLineException("Duplicate flag: " + flag); - } - this.parsed.put(argFlag, args); - } - - private int parseOutput(int i) throws CommandLineException - { - if ((i + 1) >= this.args.length) - { - throw new CommandLineException("Missing directory argument"); - } - String dir = this.args[++i]; - this.parsed.put(CLArgParser.UNIQUE_FLAGS.get(CLArgParser.API_OUTPUT_DIR_FLAG), new String[] { dir } ); - return i; - } - - private void parseMain(int i) throws CommandLineException - { - String main = args[i]; - if (!CLArgParser.validateModuleArg(main)) - { - throw new CommandLineException("Bad module arg: " + main); - } - this.parsed.put(CLArgFlag.MAIN_MOD, new String[] { main } ); - } - - private int parseImportPath(int i) throws CommandLineException - { - if ((i + 1) >= this.args.length) - { - throw new CommandLineException("Missing path argument"); - } - String path = this.args[++i]; - if (!validatePaths(path)) - { - throw new CommandLineException("Scribble module import path '"+ path +"' is not valid\r\n"); - } - //this.parsed.put(CommandLineArgParser.FLAGS.get(CommandLineArgParser.PATH_FLAG), new String[] { path }); - checkAndAddUniqueFlag(CLArgParser.IMPORT_PATH_FLAG, new String[] { path }); - return i; - } - - private int parseInlineMainModule(int i) throws CommandLineException - { - if ((i + 1) >= this.args.length) - { - throw new CommandLineException("Missing module definition"); - } - String inline = this.args[++i]; - checkAndAddUniqueFlag(CLArgParser.INLINE_MAIN_MOD_FLAG, new String[] { inline }); - return i; - } - - private int parseProject(int i) throws CommandLineException // Similar to parseProtoAndRoleArgs - { - if ((i + 2) >= this.args.length) - { - throw new CommandLineException("Missing protocol/role arguments"); - } - String proto = this.args[++i]; - String role = this.args[++i]; - /*if (!validateProtocolName(proto)) // TODO - { - throw new RuntimeException("Protocol name '"+ proto +"' is not valid\r\n"); - }*/ - concatArgs(CLArgParser.NON_UNIQUE_FLAGS.get(CLArgParser.PROJECT_FLAG), proto, role); - return i; - } - - private int parseProtoAndRoleArgs(String f, int i) throws CommandLineException - { - CLArgFlag flag = CLArgParser.NON_UNIQUE_FLAGS.get(f); - if ((i + 2) >= this.args.length) - { - throw new CommandLineException("Missing protocol/role arguments"); - } - String proto = this.args[++i]; - String role = this.args[++i]; - concatArgs(flag, proto, role); - return i; - } - - protected int parseProtoRoleAndFileArgs(String f, int i) throws CommandLineException - { - CLArgFlag flag = CLArgParser.NON_UNIQUE_FLAGS.get(f); - if ((i + 3) >= this.args.length) + int num = this.flags.explicit.get(lab).numArgs; + if ((i + num) >= this.raw.length) { - throw new CommandLineException("Missing protocol/role/file arguments"); + throw new CommandLineException(this.flags.explicit.get(lab).err); } - String proto = this.args[++i]; - String role = this.args[++i]; - String png = this.args[++i]; - concatArgs(flag, proto, role, png); - return i; - } - - private int parseProtoArg(String f, int i) throws CommandLineException - { - CLArgFlag flag = CLArgParser.NON_UNIQUE_FLAGS.get(f); - if ((i + 1) >= this.args.length) + String[] flagArgs = new String[num]; + if (num > 0) { - throw new CommandLineException("Missing protocol argument"); + System.arraycopy(this.raw, i+1, flagArgs, 0, num); } - String proto = this.args[++i]; - concatArgs(flag, proto); - return i; + this.parsed.add(new Pair<>(lab, flagArgs)); + return i+1 + num; } - private int parseProtoAndFileArgs(String f, int i) throws CommandLineException + // Puts into this.parsed + protected int parseMain(int i) throws CommandLineException { - CLArgFlag flag = CLArgParser.NON_UNIQUE_FLAGS.get(f); - if ((i + 2) >= this.args.length) - { - throw new CommandLineException("Missing protocol/file arguments"); - } - String proto = this.args[++i]; - String png = this.args[++i]; - concatArgs(flag, proto, png); - return i; + String main = this.raw[i]; + this.parsed.add(new Pair<>(CLFlags.MAIN_MOD_FLAG, new String[]{main})); + return i+1; } - private void concatArgs(CLArgFlag flag, String... toAdd) + private boolean isMainModuleParsed() { - String[] args = this.parsed.get(flag); - if (args == null) - { - args = Arrays.copyOf(toAdd, toAdd.length); - } - else - { - String[] tmp = new String[args.length + toAdd.length]; - System.arraycopy(args, 0, tmp, 0, args.length); - System.arraycopy(toAdd, 0, tmp, args.length, toAdd.length); - args = tmp; - } - this.parsed.put(flag, args); + List labs = getParsedKeys(); + return labs.contains(CLFlags.MAIN_MOD_FLAG) + || labs.contains(CLFlags.INLINE_MAIN_MOD_FLAG); } - // Used to guard subsequent file open attempt? - private static boolean validateModuleArg(String arg) + // 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) + return arg.chars() + .noneMatch(i -> !Character.isLetterOrDigit(i) && i != '.' + && i != File.separatorChar && i != ':' && i != '-' && i != '_' + && i != '/'); // Hack? (cygwin) } - private static boolean validatePaths(String paths) + private boolean validatePaths(String paths) { for (String path : paths.split(File.pathSeparator)) { @@ -422,4 +160,18 @@ private static boolean validatePaths(String paths) } 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 index 20f9ebfca..6b1d78698 100644 --- a/scribble-cli/src/main/java/org/scribble/cli/CommandLine.java +++ b/scribble-cli/src/main/java/org/scribble/cli/CommandLine.java @@ -14,111 +14,243 @@ 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.ProtocolDecl; -import org.scribble.ast.global.GProtocolDecl; +import org.scribble.ast.ProtoDecl; +import org.scribble.ast.global.GProtoDecl; import org.scribble.codegen.java.JEndpointApiGenerator; -import org.scribble.main.AntlrSourceException; -import org.scribble.main.Job; -import org.scribble.main.JobContext; -import org.scribble.main.MainContext; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; -import org.scribble.main.resource.DirectoryResourceLocator; -import org.scribble.main.resource.ResourceLocator; -import org.scribble.model.endpoint.EGraph; -import org.scribble.model.global.SGraph; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.LProtocolName; -import org.scribble.type.name.Role; +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 Map args; // Maps each flag to list of associated argument values + protected final CLFlags flags; + protected final List> args; + // left = CLFlags String constant, right = flag args (if any) -- ordered by parsing order - protected CommandLine(CLArgParser p) throws CommandLineException + 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) { - p.parse(); - this.args = p.getArgs(); + return this.args.stream().anyMatch(x -> x.left.equals(flag)); } - public CommandLine(String... args) throws CommandLineException + private String[] getUniqueFlagArgs(String flag) { - //this.args = new CLArgParser(args).getArgs(); - this(new CLArgParser(args)); - if (!this.args.containsKey(CLArgFlag.MAIN_MOD) && !this.args.containsKey(CLArgFlag.INLINE_MAIN_MOD)) - { - throw new CommandLineException("No main module has been specified\r\n"); - } + return this.args.stream().filter(x -> x.left.equals(flag)).findAny() + .get().right; + } + + protected CLFlags newCLFlags() + { + return new CLFlags(); } - // A Scribble extension should override newMainContext as appropriate. - protected MainContext newMainContext() throws ScribParserException, ScribbleException + // A Scribble extension should override as appropriate + protected CLArgParser newCLArgParser(CLFlags flags, String[] args) { - //boolean jUnit = this.args.containsKey(ArgFlag.JUNIT); - boolean debug = this.args.containsKey(CLArgFlag.VERBOSE); // TODO: factor out (cf. MainContext fields) - boolean useOldWF = this.args.containsKey(CLArgFlag.OLD_WF); - boolean noLiveness = this.args.containsKey(CLArgFlag.NO_LIVENESS); - boolean minEfsm = this.args.containsKey(CLArgFlag.LTSCONVERT_MIN); - boolean fair = this.args.containsKey(CLArgFlag.FAIR); - boolean noLocalChoiceSubjectCheck = this.args.containsKey(CLArgFlag.NO_LOCAL_CHOICE_SUBJECT_CHECK); - boolean noAcceptCorrelationCheck = this.args.containsKey(CLArgFlag.NO_ACCEPT_CORRELATION_CHECK); - boolean noValidation = this.args.containsKey(CLArgFlag.NO_VALIDATION); + return new CLArgParser(flags, args); + } - List impaths = this.args.containsKey(CLArgFlag.IMPORT_PATH) - ? CommandLine.parseImportPaths(this.args.get(CLArgFlag.IMPORT_PATH)[0]) - : Collections.emptyList(); - ResourceLocator locator = new DirectoryResourceLocator(impaths); - if (this.args.containsKey(CLArgFlag.INLINE_MAIN_MOD)) + // 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)) { - return new MainContext(debug, locator, this.args.get(CLArgFlag.INLINE_MAIN_MOD)[0], useOldWF, noLiveness, minEfsm, fair, - noLocalChoiceSubjectCheck, noAcceptCorrelationCheck, noValidation); + String inline = getUniqueFlagArgs(CLFlags.INLINE_MAIN_MOD_FLAG)[0]; + return new Main(inline, args); } else { - Path mainpath = CommandLine.parseMainPath(this.args.get(CLArgFlag.MAIN_MOD)[0]); - //return new MainContext(jUnit, debug, locator, mainpath, useOldWF, noLiveness); - return new MainContext(debug, locator, mainpath, useOldWF, noLiveness, minEfsm, fair, - noLocalChoiceSubjectCheck, noAcceptCorrelationCheck, noValidation); + 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 + public static void main(String[] args) + throws CommandLineException, AntlrSourceException { new CommandLine(args).run(); } - public void run() throws CommandLineException, AntlrSourceException // ScribbleException is for JUnit testing + public void run() throws CommandLineException, + AntlrSourceException // For JUnit harness (ScribException) { try { try { - runBody(); + runTasks(); } - catch (ScribbleException e) // Wouldn't need to do this if not Runnable (so maybe change) + catch (ScribException e) // Wouldn't need to do this if not Runnable (so maybe change) { - if (this.args.containsKey(CLArgFlag.JUNIT) || this.args.containsKey(CLArgFlag.VERBOSE)) + if (hasFlag(CLFlags.JUNIT_FLAG) // JUnit harness looks for an exception + || hasFlag(CLFlags.VERBOSE_FLAG)) // Also print full trace for -V { - /*RuntimeScribbleException ee = new RuntimeScribbleException(e.getMessage()); - ee.setStackTrace(e.getStackTrace()); - throw ee;*/ throw e; } else { - System.err.println(e.getMessage()); // JUnit harness looks for an exception + System.err.println(e.getMessage()); System.exit(1); } } @@ -128,336 +260,253 @@ public void run() throws CommandLineException, AntlrSourceException // Scribble System.err.println(e.getMessage()); // No need to give full stack trace, even for debug, for command line errors System.exit(1); } - catch (RuntimeScribbleException e) + catch (RuntimeScribException e) { System.err.println(e.getMessage()); System.exit(1); } } - protected void runBody() throws ScribParserException, AntlrSourceException, CommandLineException + protected void runTasks() + throws AntlrSourceException, ScribParserException, CommandLineException { - MainContext mc = newMainContext(); - Job job = mc.newJob(); - ScribbleException fail = null; - try - { - doValidationTasks(job); - } - catch (ScribbleException x) - { - fail = x; - } - - // Attempt certain "output tasks" even if above failed, in case can still do some useful output (hacky) - try - { - tryOutputTasks(job); - } - catch (ScribbleException x) - { - if (fail == null) - { - fail = x; - } - } - - if (fail != null) // Well-formedness check and/or an "attemptable output task" failed - { - throw fail; - } - - // "Non-attemptable" output tasks: should not attempt these if any previous failure - doNonAttemptableOutputTasks(job); - } - - // AntlrSourceException super of ScribbleException -- needed for, e.g., AssrtCoreSyntaxException - protected void doValidationTasks(Job job) throws AntlrSourceException, ScribParserException, // Latter in case needed by subclasses - CommandLineException - { - /*// Scribble extensions (custom Job passes) - if (this.args.containsKey(F17CLArgFlag.F17)) - { - GProtocolName simpname = new GProtocolName(this.args.get(ArgFlag.F17)[0]); - F17Main.parseAndCheckWF(job, simpname); // Includes base passes - } - - // Base Scribble - else*/ - { - job.checkWellFormedness(); - } - } - - protected void tryOutputTasks(Job job) throws CommandLineException, ScribbleException - { - // Following must be ordered appropriately -- ? - if (this.args.containsKey(CLArgFlag.PROJECT)) - { - printProjections(job); - } - if (this.args.containsKey(CLArgFlag.EFSM)) - { - printEGraph(job, true, true); - } - if (this.args.containsKey(CLArgFlag.VALIDATION_EFSM)) - { - printEGraph(job, false, true); - } - if (this.args.containsKey(CLArgFlag.UNFAIR_EFSM)) - { - printEGraph(job, false, false); - } - if (this.args.containsKey(CLArgFlag.EFSM_PNG)) - { - drawEGraph(job, true, true); - } - if (this.args.containsKey(CLArgFlag.VALIDATION_EFSM_PNG)) - { - drawEGraph(job, false, true); - } - if (this.args.containsKey(CLArgFlag.UNFAIR_EFSM_PNG)) - { - drawEGraph(job, false, false); - } - if (this.args.containsKey(CLArgFlag.SGRAPH) || this.args.containsKey(CLArgFlag.SGRAPH_PNG) - || this.args.containsKey(CLArgFlag.UNFAIR_SGRAPH) || this.args.containsKey(CLArgFlag.UNFAIR_SGRAPH_PNG)) - { - if (job.useOldWf) - { - throw new CommandLineException("Global model flag(s) incompatible with: " + CLArgParser.OLD_WF_FLAG); - } - if (this.args.containsKey(CLArgFlag.SGRAPH)) - { - printSGraph(job, true); - } - if (this.args.containsKey(CLArgFlag.UNFAIR_SGRAPH)) + 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) { - printSGraph(job, false); + continue; } - if (this.args.containsKey(CLArgFlag.SGRAPH_PNG)) + if (!flag.barrier) { - drawSGraph(job, true); + try { tryNonBarrierTask(job, a); } + catch (ScribException x) { if (err == null) { err = x; } } } - if (this.args.containsKey(CLArgFlag.UNFAIR_SGRAPH_PNG)) + else { - drawSGraph(job, false); + if (err == null) + { + try { tryBarrierTask(job, a); } + catch (ScribException x) { err = x; } + } } } - } - - // FIXME: rename - protected void doNonAttemptableOutputTasks(Job job) throws ScribbleException, CommandLineException - { - if (this.args.containsKey(CLArgFlag.SESS_API_GEN)) - { - outputSessionApi(job); - } - if (this.args.containsKey(CLArgFlag.SCHAN_API_GEN)) + if (err != null) { - outputStateChannelApi(job); - } - if (this.args.containsKey(CLArgFlag.API_GEN)) - { - outputEndpointApi(job); + throw err; } } - // FIXME: option to write to file, like classes - private void printProjections(Job job) throws CommandLineException, ScribbleException + // TODO: option to write to file, like API classes + private void printProjection(Job job, String[] args) + throws CommandLineException, ScribException { - JobContext jcontext = job.getContext(); - String[] args = this.args.get(CLArgFlag.PROJECT); + JobContext jobc = job.getContext(); for (int i = 0; i < args.length; i += 2) { - GProtocolName fullname = checkGlobalProtocolArg(jcontext, args[i]); - Role role = checkRoleArg(jcontext, fullname, args[i+1]); - Map projections = job.getProjections(fullname, role); - System.out.println("\n" + projections.values().stream().map((p) -> p.toString()).collect(Collectors.joining("\n\n"))); + 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 printEGraph(Job job, boolean forUser, boolean fair) throws ScribbleException, CommandLineException + private void outputEGraph(Job job, String[] args, boolean forUser, + boolean fair, boolean draw) throws ScribException, CommandLineException { - JobContext jcontext = job.getContext(); - String[] args = forUser ? this.args.get(CLArgFlag.EFSM) : (fair ? this.args.get(CLArgFlag.VALIDATION_EFSM) : this.args.get(CLArgFlag.UNFAIR_EFSM)); - for (int i = 0; i < args.length; i += 2) - { - GProtocolName fullname = checkGlobalProtocolArg(jcontext, args[i]); - Role role = checkRoleArg(jcontext, fullname, args[i+1]); + 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); - String out = this.args.containsKey(CLArgFlag.AUT) ? fsm.toAut() : fsm.toDot(); - System.out.println("\n" + out); // Endpoint graphs are "inlined" (a single graph is built) + 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 drawEGraph(Job job, boolean forUser, boolean fair) throws ScribbleException, CommandLineException + private void outputEndpointApi(Job job, String[] args, boolean sess, + boolean schan, boolean cb) throws ScribException, CommandLineException { - JobContext jcontext = job.getContext(); - String[] args = forUser ? this.args.get(CLArgFlag.EFSM_PNG) : (fair ? this.args.get(CLArgFlag.VALIDATION_EFSM_PNG) : this.args.get(CLArgFlag.UNFAIR_EFSM_PNG)); - for (int i = 0; i < args.length; i += 3) + JobContext jobc = job.getContext(); + JEndpointApiGenerator jgen = new JEndpointApiGenerator(job); // FIXME: refactor (generalise -- use new API) { - GProtocolName fullname = checkGlobalProtocolArg(jcontext, args[i]); - Role role = checkRoleArg(jcontext, fullname, args[i+1]); - String png = args[i+2]; - EGraph fsm = getEGraph(job, fullname, role, forUser, fair); - runDot(fsm.toDot(), png); + 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, GProtocolName fullname, Role role, boolean forUser, boolean fair) - throws ScribbleException, CommandLineException + private EGraph getEGraph(Job job, GProtoName fullname, Role role, + boolean forUser, boolean fair) + throws ScribException, CommandLineException { - JobContext jcontext = job.getContext(); - GProtocolDecl gpd = (GProtocolDecl) jcontext.getMainModule().getProtocolDecl(fullname.getSimpleName()); - if (gpd == null || !gpd.header.roledecls.getRoles().contains(role)) + 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: " + Arrays.toString(this.args.get(CLArgFlag.DOT))); + throw new CommandLineException("Bad FSM construction args: " + + gpd + ", " + role); } EGraph graph; if (forUser) // The (possibly minimised) user-output EFSM for API gen { - graph = this.args.containsKey(CLArgFlag.LTSCONVERT_MIN) - ? jcontext.getMinimisedEGraph(fullname, role) : jcontext.getEGraph(fullname, role); + 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 - ? jcontext.getUnfairEGraph(fullname, role) : jcontext.getEGraph(fullname, role); + ? corec.getUnfairEGraph(fullname, role) + : corec.getEGraph(fullname, role); } if (graph == null) { - throw new RuntimeScribbleException("Shouldn't see this: " + fullname); // Should be suppressed by an earlier failure + throw new RuntimeScribException("Shouldn't see this: " + fullname); + // Should be caught by some earlier failure } return graph; } - private void printSGraph(Job job, boolean fair) throws ScribbleException, CommandLineException + private SGraph getSGraph(Job job, GProtoName fullname, boolean fair) + throws ScribException { - JobContext jcontext = job.getContext(); - String[] args = fair ? this.args.get(CLArgFlag.SGRAPH) : this.args.get(CLArgFlag.UNFAIR_SGRAPH); - for (int i = 0; i < args.length; i += 1) - { - GProtocolName fullname = checkGlobalProtocolArg(jcontext, args[i]); - SGraph model = getSGraph(job, fullname, fair); - String out = this.args.containsKey(CLArgFlag.AUT) ? model.toAut() : model.toDot(); - System.out.println("\n" + out); - } - } - - private void drawSGraph(Job job, boolean fair) throws ScribbleException, CommandLineException - { - JobContext jcontext = job.getContext(); - String[] args = fair ? this.args.get(CLArgFlag.SGRAPH_PNG) : this.args.get(CLArgFlag.UNFAIR_SGRAPH_PNG); - for (int i = 0; i < args.length; i += 2) - { - GProtocolName fullname = checkGlobalProtocolArg(jcontext, args[i]); - String png = args[i+1]; - SGraph model = getSGraph(job, fullname, fair); - runDot(model.toDot(), png); - } - } - - private static SGraph getSGraph(Job job, GProtocolName fullname, boolean fair) throws ScribbleException - { - JobContext jcontext = job.getContext(); - SGraph model = fair ? jcontext.getSGraph(fullname) : jcontext.getUnfairSGraph(fullname); + CoreContext jobc2 = job.getCore().getContext(); + SGraph model = fair + ? jobc2.getSGraph(fullname) + : jobc2.getUnfairSGraph(fullname); if (model == null) { - throw new RuntimeScribbleException("Shouldn't see this: " + fullname); // Should be suppressed by an earlier failure + throw new RuntimeScribException("Shouldn't see this: " + fullname); + // Should be caught by some earlier failure } return model; } - private void outputEndpointApi(Job job) throws ScribbleException, CommandLineException - { - JobContext jcontext = job.getContext(); - String[] args = this.args.get(CLArgFlag.API_GEN); - JEndpointApiGenerator jgen = new JEndpointApiGenerator(job); // FIXME: refactor (generalise -- use new API) - for (int i = 0; i < args.length; i += 2) - { - GProtocolName fullname = checkGlobalProtocolArg(jcontext, args[i]); - Map sessClasses = jgen.generateSessionApi(fullname); - outputClasses(sessClasses); - Role role = checkRoleArg(jcontext, fullname, args[i+1]); - Map scClasses = jgen.generateStateChannelApi(fullname, role, this.args.containsKey(CLArgFlag.SCHAN_API_SUBTYPES)); - outputClasses(scClasses); - } - } - - private void outputSessionApi(Job job) throws ScribbleException, CommandLineException - { - JobContext jcontext = job.getContext(); - String[] args = this.args.get(CLArgFlag.SESS_API_GEN); - JEndpointApiGenerator jgen = new JEndpointApiGenerator(job); // FIXME: refactor (generalise -- use new API) - for (String fullname : args) - { - GProtocolName gpn = checkGlobalProtocolArg(jcontext, fullname); - Map classes = jgen.generateSessionApi(gpn); - outputClasses(classes); - } - } - - private void outputStateChannelApi(Job job) throws ScribbleException, CommandLineException - { - JobContext jcontext = job.getContext(); - String[] args = this.args.get(CLArgFlag.SCHAN_API_GEN); - JEndpointApiGenerator jgen = new JEndpointApiGenerator(job); // FIXME: refactor (generalise -- use new API) - for (int i = 0; i < args.length; i += 2) - { - GProtocolName fullname = checkGlobalProtocolArg(jcontext, args[i]); - Role role = checkRoleArg(jcontext, fullname, args[i+1]); - Map classes = jgen.generateStateChannelApi(fullname, role, this.args.containsKey(CLArgFlag.SCHAN_API_SUBTYPES)); - outputClasses(classes); - } - } - - // filepath -> class source - protected void outputClasses(Map classes) throws ScribbleException + // classes: filepath -> class source + protected void outputClasses(Map classes) + throws ScribException { Consumer f; - if (this.args.containsKey(CLArgFlag.API_OUTPUT)) + if (hasFlag(CLFlags.API_OUTPUT_DIR_FLAG)) { - String dir = this.args.get(CLArgFlag.API_OUTPUT)[0]; + String dir = getUniqueFlagArgs(CLFlags.API_OUTPUT_DIR_FLAG)[0]; f = path -> { ScribUtil.handleLambdaScribbleException(() -> - { - String tmp = dir + "/" + path; - if (this.args.containsKey(CLArgFlag.VERBOSE)) - { - System.out.println("[DEBUG] Writing to: " + tmp); - } - ScribUtil.writeToFile(tmp, classes.get(path)); return null; - }); }; + { + 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().stream().forEach(f); + classes.keySet().forEach(f); } - protected static void runDot(String dot, String png) throws ScribbleException, CommandLineException + protected static void runDot(String dot, String png) + throws ScribException, CommandLineException { - String tmpName = png + ".tmp"; - File tmp = new File(tmpName); - if (tmp.exists()) - { - throw new CommandLineException("Cannot overwrite: " + tmpName); - } + 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 { - tmp.delete(); + if (tmp != null) + { + tmp.delete(); + } } } @@ -468,36 +517,42 @@ protected static Path parseMainPath(String path) protected static List parseImportPaths(String paths) { - return Arrays.stream(paths.split(File.pathSeparator)).map((s) -> Paths.get(s)).collect(Collectors.toList()); + return Arrays.stream(paths.split(File.pathSeparator)).map(s -> Paths.get(s)) + .collect(Collectors.toList()); } - protected static GProtocolName checkGlobalProtocolArg(JobContext jcontext, String simpname) throws CommandLineException + protected static GProtoName checkGlobalProtocolArg(JobContext jobc, + String simpname) throws CommandLineException { - GProtocolName simpgpn = new GProtocolName(simpname); - Module main = jcontext.getMainModule(); - if (!main.hasProtocolDecl(simpgpn)) + GProtoName simpgpn = new GProtoName(simpname); + Module main = jobc.getMainModule(); + if (!main.hasGProtocolDecl(simpgpn)) { throw new CommandLineException("Global protocol not found: " + simpname); } - ProtocolDecl pd = main.getProtocolDecl(simpgpn); + ProtoDecl pd = main.getGProtocolDeclChild(simpgpn); if (pd == null || !pd.isGlobal()) { throw new CommandLineException("Global protocol not found: " + simpname); } - if (pd.isAuxModifier()) // CHECKME: maybe don't check for all, e.g. -project + if (pd.isAux()) // CHECKME: maybe don't check for all, e.g. -project { - throw new CommandLineException("Invalid aux protocol specified as root: " + simpname); + throw new CommandLineException( + "Invalid aux protocol specified as root: " + simpname); } - return new GProtocolName(jcontext.main, simpgpn); + return new GProtoName(jobc.job.config.main, simpgpn); // TODO: take Job param instead of Jobcontext } - protected static Role checkRoleArg(JobContext jcontext, GProtocolName fullname, String rolename) throws CommandLineException + protected static Role checkRoleArg(JobContext jobc, + GProtoName fullname, String rolename) throws CommandLineException { - ProtocolDecl pd = jcontext.getMainModule().getProtocolDecl(fullname.getSimpleName()); + ProtoDecl pd = jobc.getMainModule() + .getGProtocolDeclChild(fullname.getSimpleName()); Role role = new Role(rolename); - if (!pd.header.roledecls.getRoles().contains(role)) + if (!pd.getHeaderChild().getRoleDeclListChild().getRoles().contains(role)) { - throw new CommandLineException("Role not declared for " + fullname + ": " + role); + throw new CommandLineException( + "Role not declared for " + fullname + ": " + role); } return role; } diff --git a/scribble-cli/src/main/java/org/scribble/main/MainContext.java b/scribble-cli/src/main/java/org/scribble/main/MainContext.java deleted file mode 100644 index 09fb36260..000000000 --- a/scribble-cli/src/main/java/org/scribble/main/MainContext.java +++ /dev/null @@ -1,202 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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; // N.B. the same package is declared in core - // FIXME? should be in core org.scribble.main, but currently here due to Maven dependency restrictions - -import java.io.File; -import java.nio.file.Path; -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.main.resource.DirectoryResourceLocator; -import org.scribble.main.resource.InlineResource; -import org.scribble.main.resource.Resource; -import org.scribble.main.resource.ResourceLocator; -import org.scribble.model.endpoint.EModelFactory; -import org.scribble.model.endpoint.EModelFactoryImpl; -import org.scribble.model.global.SModelFactory; -import org.scribble.model.global.SModelFactoryImpl; -import org.scribble.parser.scribble.ScribbleAntlrWrapper; -import org.scribble.parser.scribble.ScribModuleLoader; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.type.name.ModuleName; -import org.scribble.util.Pair; -import org.scribble.util.ScribParserException; - -// Scribble tool context for main module -// MainContext takes ResourceLocator abstractly (e.g. DirectoryResourceLocator), but because abstract Resource itself works off paths, it takes mainpath (rather than something more abstract, e.g. URI, to identify the "main" resource) -// Resource and ResourceLocator should be made abstract from (file)paths (cf. use of toPath in ScribbleModuleLoader) -public class MainContext -{ - - // Only "manually" used here for loading main module (which should be factored out to front end) -- otherwise, only used within loader - protected final ScribbleAntlrWrapper antlrParser = newAntlrParser(); // Not encapsulated inside ScribbleParser, because ScribbleParser's main function is to "parse" ANTLR CommonTrees into ModelNodes - protected final AntlrToScribParser scribParser = newScribParser(); - - protected final AstFactory af = newAstFactory(); - protected final EModelFactory ef = newEModelFactory(); - protected final SModelFactory sf = newSModelFactory(); - - //protected final JScribbleApiGen jgen; // No: API gen depends on the Job - - //public final boolean jUnit; - public final boolean debug; // TODO: factor out with Job -- (cf. CommandLine.newMainContext) - public final boolean useOldWF; - public final boolean noLiveness; - public final boolean minEfsm; - public final boolean fair; - public final boolean noLocalChoiceSubjectCheck; - public final boolean noAcceptCorrelationCheck; - public final boolean noValidation; - - private final ResourceLocator locator; // Path -> Resource - private final ScribModuleLoader loader; // sesstype.ModuleName -> Pair - - protected ModuleName main; - - // ModuleName keys are full module 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<>(); - - // FIXME: make Path abstract as e.g. URI -- locator is abstract but Path is coupled to concrete DirectoryResourceLocator - private MainContext(boolean debug, ResourceLocator locator, boolean useOldWF, boolean noLiveness, boolean minEfsm, - boolean fair, boolean noLocalChoiceSubjectCheck, boolean noAcceptCorrelationCheck, boolean noValidation) - throws ScribParserException, ScribbleException - { - //this.jUnit = jUnit; - this.debug = debug; - this.useOldWF = useOldWF; - this.noLiveness = noLiveness; - this.minEfsm = minEfsm; - this.fair = fair; - this.noLocalChoiceSubjectCheck = noLocalChoiceSubjectCheck; - this.noAcceptCorrelationCheck = noAcceptCorrelationCheck; - this.noValidation = noValidation; - - this.locator = locator; - this.loader = new ScribModuleLoader(this.locator, this.antlrParser, this.scribParser); - } - - // Load main module from file system - public MainContext(boolean debug, ResourceLocator locator, Path mainpath, boolean useOldWF, boolean noLiveness, boolean minEfsm, - boolean fair, boolean noLocalChoiceSubjectCheck, boolean noAcceptCorrelationCheck, boolean noValidation) - throws ScribParserException, ScribbleException - { - this(debug, locator, useOldWF, noLiveness, minEfsm, fair, noLocalChoiceSubjectCheck, noAcceptCorrelationCheck, noValidation); - - // FIXME: checking main module resource exists at specific location should be factored out to front-end (e.g. CommandLine) -- main module resource is specified at local front end level of abstraction, while MainContext uses abstract resource loading - //Pair p = this.loader.loadMainModule(mainpath); - Resource res = DirectoryResourceLocator.getResourceByFullPath(mainpath); // FIXME: hardcoded to DirectoryResourceLocator -- main module loading should be factored out to front end (e.g. CommandLine) - Module mod = (Module) this.scribParser.parse(this.antlrParser.parseAntlrTree(res), this.af); // FIXME: rename exceptions - checkMainModuleName(mainpath, mod); - - init(res, mod); - } - - // For inline module arg - public MainContext(boolean debug, ResourceLocator locator, String inline, boolean useOldWF, boolean noLiveness, boolean minEfsm, - boolean fair, boolean noLocalChoiceSubjectCheck, boolean noAcceptCorrelationCheck, boolean noValidation) - throws ScribParserException, ScribbleException - { - this(debug, locator, useOldWF, noLiveness, minEfsm, fair, noLocalChoiceSubjectCheck, noAcceptCorrelationCheck, noValidation); - - Resource res = new InlineResource(inline); - Module mod = (Module) this.scribParser.parse(this.antlrParser.parseAntlrTree(res), this.af); - - init(res, mod); - } - - private void init(Resource res, Module mainmod) throws ScribParserException, ScribbleException - { - Pair p = new Pair<>(res, mainmod); - this.main = p.right.getFullModuleName(); // FIXME: main modname comes from the inlined moddecl -- check for issues if this clashes with an existing file system resource - loadAllModules(p); - } - - // A Scribble extension should override these "new" methods as appropriate. - public Job newJob() - { - return new Job(this.debug, this.getParsedModules(), this.main, this.useOldWF, this.noLiveness, this.minEfsm, this.fair, - this.noLocalChoiceSubjectCheck, this.noAcceptCorrelationCheck, this.noValidation, - this.af, this.ef, this.sf); - } - - protected ScribbleAntlrWrapper newAntlrParser() - { - return new ScribbleAntlrWrapper(); - } - - protected AntlrToScribParser newScribParser() - { - return new AntlrToScribParser(); - } - - protected AstFactory newAstFactory() - { - return new AstFactoryImpl(); - } - - protected EModelFactory newEModelFactory() - { - return new EModelFactoryImpl(); - } - - protected SModelFactory newSModelFactory() - { - return new SModelFactoryImpl(); - } - - private void loadAllModules(Pair module) throws ScribParserException, ScribbleException - { - this.parsed.put(module.right.getFullModuleName(), module); - for (ImportDecl id : module.right.getImportDecls()) - { - if (id.isImportModule()) - { - ModuleName modname = ((ImportModule) id).modname.toName(); - if (!this.parsed.containsKey(modname)) - { - loadAllModules(this.loader.loadModule(modname, af)); - } - } - } - } - - public Map getParsedModules() - { - return this.parsed.entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> e.getValue().right)); - } - - // Hacky? But not Scribble tool's job to check nested directory location of module fully corresponds to the fullname of module? Cf. Java classes - private void checkMainModuleName(Path mainpath, Module main) throws ScribbleException - { - String path = mainpath.toString(); // FIXME: hack - // FileSystems.getDefault().getSeparator() ? - String tmp = path.substring((path.lastIndexOf(File.separator) == -1) ? 0 : path.lastIndexOf(File.separator) + 1, path.lastIndexOf('.')); - if (!this.noValidation) - { - if (!tmp.equals(main.getFullModuleName().getSimpleName().toString())) // ModuleName.toString hack? - { - throw new ScribbleException(main.moddecl.name.getSource(), "Simple module name at path " + path + " mismatch: " + main.getFullModuleName()); - } - } - } -} diff --git a/scribble-codegen/pom.xml b/scribble-codegen/pom.xml index e3fba955c..058edd750 100644 --- a/scribble-codegen/pom.xml +++ b/scribble-codegen/pom.xml @@ -1,24 +1,30 @@ - + 4.0.0 - - org.scribble - parent - 0.4.4-SNAPSHOT - + + scribble-codegen - scribble-codegen - http://maven.apache.org - - UTF-8 - 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/endpointapi/ApiGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/ApiGen.java similarity index 77% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ApiGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/ApiGen.java index 206dc38e5..08c02557f 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ApiGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/ApiGen.java @@ -11,22 +11,25 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi; +package org.scribble.codegen.java; import java.util.Map; -import org.scribble.main.Job; -import org.scribble.type.name.GProtocolName; +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 { - protected final Job job; - protected final GProtocolName gpn; // full name + public final Job job; + public final Core core; + public final GProtoName gpn; // full name - public ApiGen(Job job, GProtocolName fullname) + public ApiGen(Job job, GProtoName fullname) { this.job = job; + this.core = job.getCore(); this.gpn = fullname; } 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 index 6e5a4eed1..c30ad3c7f 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/JEndpointApiGenerator.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/JEndpointApiGenerator.java @@ -16,14 +16,14 @@ import java.util.HashMap; import java.util.Map; -import org.scribble.codegen.java.endpointapi.SessionApiGenerator; -import org.scribble.codegen.java.endpointapi.StateChannelApiGenerator; -import org.scribble.codegen.java.endpointapi.ioifaces.IOInterfacesGenerator; -import org.scribble.main.Job; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.Role; +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 { @@ -34,33 +34,39 @@ public JEndpointApiGenerator(Job job) this.job = job; } - public Map generateSessionApi(GProtocolName fullname) throws ScribbleException + public Map generateSessionApi(GProtoName fullname) + throws ScribException { - this.job.debugPrintln("\n[Java API gen] Running " + SessionApiGenerator.class + " for " + fullname); + 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; } - // FIXME: refactor an EndpointApiGenerator -- ? - public Map generateStateChannelApi(GProtocolName fullname, Role self, boolean subtypes) throws ScribbleException + // 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.debugPrintln("\n[Java API gen] Running " + StateChannelApiGenerator.class + " for " + fullname + "@" + self); - StateChannelApiGenerator apigen = new StateChannelApiGenerator(this.job, 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 (RuntimeScribbleException e) // FIXME: use IOInterfacesGenerator.skipIOInterfacesGeneration + 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()); + 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? 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/endpointapi/StateChannelApiGenerator.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/StateChannelApiGenerator.java deleted file mode 100644 index 11c7f703e..000000000 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/StateChannelApiGenerator.java +++ /dev/null @@ -1,221 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.endpointapi; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import org.scribble.ast.Module; -import org.scribble.codegen.java.util.ClassBuilder; -import org.scribble.codegen.java.util.TypeBuilder; -import org.scribble.main.Job; -import org.scribble.main.JobContext; -import org.scribble.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.LProtocolName; -import org.scribble.type.name.Role; -import org.scribble.visit.context.Projector; - -// 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.net.ScribMessage"; - public static final String SCRIBBLERUNTIMEEXCEPTION_CLASS = "org.scribble.main.ScribbleRuntimeException"; - public static final String RECEIVE_OP_PARAM = "op"; - public static final String SCRIBMESSAGE_OP_FIELD = "op"; - - private final Role self; - private final LProtocolName 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, GProtocolName fullname, Role self) throws ScribbleException // FIXME: APIGenerationException? - { - super(job, fullname); - - this.self = self; - this.lpn = Projector.projectFullProtocolName(fullname, self); - //this.init = job.getContext().getEndpointGraph(fullname, self).init; - JobContext jc = job.getContext(); - this.init = job.minEfsm ? jc.getMinimisedEGraph(fullname, self).init : jc.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 = EState.getTerminal(this.init); - 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 = EState.getReachableActions(init); - 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('.', '/') + "/channels/" + 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.getAllSuccessors()) - { - generateClassNames(succ); - } - } - - private String newSocketClassName() - { - return this.lpn.getSimpleName().toString() + "_" + this.counter++; - } - - private void constructClasses(EState curr) throws ScribbleException - { - 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.getAllSuccessors()) - { - 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 ScribbleException // 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_INPUT: - { - return new ReceiveSockGen(this, curr).generateType(); - } - case POLY_INPUT: - { - // Receive only - return new BranchSockGen(this, curr).generateType(); - } - default: - { - throw new RuntimeException("[TODO] State Channel API generation not supported for: " + curr.getStateKind() + ", " + curr.toLongString()); - } - } - } - - public GProtocolName 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/endpointapi/ioifaces/ReceiveIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/ReceiveIfaceGen.java deleted file mode 100644 index 6567d5bc7..000000000 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/ReceiveIfaceGen.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.endpointapi.ioifaces; - -import java.util.Map; - -import org.scribble.codegen.java.endpointapi.InputFutureGen; -import org.scribble.codegen.java.endpointapi.ReceiveSockGen; -import org.scribble.codegen.java.endpointapi.ScribSockGen; -import org.scribble.codegen.java.endpointapi.SessionApiGenerator; -import org.scribble.codegen.java.endpointapi.StateChannelApiGenerator; -import org.scribble.codegen.java.util.InterfaceBuilder; -import org.scribble.codegen.java.util.MethodBuilder; -import org.scribble.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.name.GProtocolName; - -public class ReceiveIfaceGen extends IOStateIfaceGen -{ - public ReceiveIfaceGen(StateChannelApiGenerator apigen, Map actions, EState curr) - { - super(apigen, actions, curr); - } - - @Override - public InterfaceBuilder generateType() throws ScribbleException - { - if (this.curr.getAllActions().stream().anyMatch((a) -> !a.isReceive())) // TODO (connect/disconnect) - { - //return null; - throw new RuntimeException("TODO: " + this.curr); - } - return super.generateType(); - } - - @Override - protected void constructInterface() throws ScribbleException - { - super.constructInterface(); - addAsyncDiscardMethod(); - } - - protected void addAsyncDiscardMethod() - { - GProtocolName gpn = this.apigen.getGProtocolName(); - EAction first = this.curr.getActions().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.getSuccessor(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/endpointapi/ioifaces/SelectIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/SelectIfaceGen.java deleted file mode 100644 index bc509e745..000000000 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/SelectIfaceGen.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.endpointapi.ioifaces; - -import java.util.Map; - -import org.scribble.codegen.java.endpointapi.StateChannelApiGenerator; -import org.scribble.codegen.java.util.InterfaceBuilder; -import org.scribble.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; - -public class SelectIfaceGen extends IOStateIfaceGen -{ - public SelectIfaceGen(StateChannelApiGenerator apigen, Map actions, EState curr) - { - super(apigen, actions, curr); - } - - @Override - public InterfaceBuilder generateType() throws ScribbleException - { - if (this.curr.getAllActions().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/endpointapi/SessionApiGenerator.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/sessionapi/SessionApiGenerator.java similarity index 78% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/SessionApiGenerator.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/sessionapi/SessionApiGenerator.java index ac4b6d022..3969e14d4 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/SessionApiGenerator.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/sessionapi/SessionApiGenerator.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi; +package org.scribble.codegen.java.sessionapi; import java.util.HashMap; import java.util.HashSet; @@ -20,39 +20,42 @@ import java.util.stream.Collectors; import org.scribble.ast.Module; -import org.scribble.ast.global.GProtocolDecl; -import org.scribble.codegen.java.util.JavaBuilder; +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.del.ModuleDel; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; -import org.scribble.visit.util.MessageIdCollector; +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.type.name.GProtocolName"; - public static final String OP_CLASS = "org.scribble.type.name.Op"; - public static final String ROLE_CLASS = "org.scribble.type.name.Role"; - public static final String SESSION_CLASS = "org.scribble.runtime.net.session.Session"; - public static final String SESSIONTYPEFACTORY_CLASS = "org.scribble.type.SessionTypeFactory"; + 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 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, GProtocolName fullname) throws ScribbleException + public SessionApiGenerator(Job job, GProtoName fullname) throws ScribException { super(job, fullname); constructRoleClasses(); @@ -72,12 +75,13 @@ public Map generateApi() Map map = new HashMap<>(); map.put(path, sb.toString()); - this.classes.keySet().stream().forEach((n) -> map.put(n, this.classes.get(n).build())); + this.classes.keySet().stream() + .forEachOrdered(n -> map.put(n, this.classes.get(n).build())); return map; } - private static String makePath(GProtocolName gpn, String simpname) + private static String makePath(GProtoName gpn, String simpname) { return getEndpointApiRootPackageName(gpn).replace('.', '/') + "/" + simpname + ".java"; } @@ -96,7 +100,7 @@ private void constructSessionClass() 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("org.scribble.type.name.Role"); + this.cb.addImports(ROLE_CLASS); this.cb.addImports(getRolesPackageName(this.gpn) + ".*"); if (!this.mids.isEmpty()) { @@ -121,8 +125,8 @@ private void constructSessionClass() fb3.setExpression(SessionApiGenerator.SESSIONTYPEFACTORY_CLASS + ".parseGlobalProtocolName(\"" + gpn + "\")"); - this.roles.stream().forEach((r) -> addRoleField(this.cb, r)); - this.mids.stream().forEach((mid) -> addOpField(this.cb, mid)); + 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); @@ -164,7 +168,7 @@ private void addRoleField(ClassBuilder cb, Role role) addSingletonConstant(cb, "roles", getRoleClassName(role)); // FIXME: factor out } - private void addOpField(ClassBuilder cb, MessageId mid) + private void addOpField(ClassBuilder cb, MsgId mid) { addSingletonConstant(cb, "ops", getOpClassName(mid)); // FIXME: factor out } @@ -178,14 +182,18 @@ private void addSingletonConstant(ClassBuilder cb, String subpack, String 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 ScribbleException + private void constructOpClasses() throws ScribException { - Module mod = this.job.getContext().getModule(this.gpn.getPrefix()); + /*Module mod = this.lang.getContext().getModule(this.gpn.getPrefix()); GProtocolName simpname = this.gpn.getSimpleName(); - GProtocolDecl gpd = (GProtocolDecl) mod.getProtocolDecl(simpname); - MessageIdCollector coll = new MessageIdCollector(this.job, ((ModuleDel) mod.del()).getModuleContext()); + GProtocolDecl gpd = (GProtocolDecl) mod.getProtocolDeclChild(simpname); + MessageIdCollector coll = new MessageIdCollector(this.lang, ((ModuleDel) mod.del()).getModuleContext()); gpd.accept(coll); - for (MessageId mid : coll.getNames()) + 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); @@ -194,12 +202,12 @@ private void constructOpClasses() throws ScribbleException } } - private void constructRoleClasses() throws ScribbleException + private void constructRoleClasses() throws ScribException { Module mod = this.job.getContext().getModule(this.gpn.getPrefix()); - GProtocolName simpname = this.gpn.getSimpleName(); - GProtocolDecl gpd = (GProtocolDecl) mod.getProtocolDecl(simpname); - for (Role r : gpd.header.roledecls.getRoles()) + 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); @@ -213,7 +221,7 @@ 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, MessageId mid) + private ClassBuilder constructOpClass(ClassBuilder cb, String pack, MsgId mid) { return constructSingletonClass(cb, pack, SessionApiGenerator.OP_CLASS, getOpClassName(mid)); } @@ -244,13 +252,13 @@ private ClassBuilder constructSingletonClass(ClassBuilder cb, String pack, Strin } // Returns the simple Session Class name - public static String getSessionClassName(GProtocolName gpn) + 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(GProtocolName gpn) + public static String getEndpointApiRootPackageName(GProtoName gpn) { //return gpn.getPrefix().getPrefix().toString(); // Java output package name (not Scribble package) // FIXME: factor out with StateChannelApiGenerator.generateClasses @@ -258,19 +266,19 @@ public static String getEndpointApiRootPackageName(GProtocolName gpn) return gpn.toString(); } - public static String getRolesPackageName(GProtocolName gpn) + public static String getRolesPackageName(GProtoName gpn) { return getEndpointApiRootPackageName(gpn) + ".roles"; } - public static String getOpsPackageName(GProtocolName gpn) + public static String getOpsPackageName(GProtoName gpn) { return getEndpointApiRootPackageName(gpn) + ".ops"; } - public static String getStateChannelPackageName(GProtocolName gpn, Role self) + public static String getStateChannelPackageName(GProtoName gpn, Role self) { - return getEndpointApiRootPackageName(gpn) + ".channels." + self; + return getEndpointApiRootPackageName(gpn) + ".statechans." + self; } // Returns the simple Role Class name @@ -280,7 +288,7 @@ public static String getRoleClassName(Role r) } // Returns the simple Op Class name: names starting with a digit are prefixed by '_' - public static String getOpClassName(MessageId mid) + 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/endpointapi/AcceptSockGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/AcceptSockGen.java similarity index 89% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/AcceptSockGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/AcceptSockGen.java index dba2bde69..b05af6f76 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/AcceptSockGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/AcceptSockGen.java @@ -11,14 +11,15 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi; +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.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; public class AcceptSockGen extends ScribSockGen { @@ -44,13 +45,13 @@ protected void addImports() protected void addMethods() { //Set as = curr.getActions(); - List 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.getSuccessor(a); + EState succ = curr.getDetSuccessor(a); makeAcceptMethod(a, succ); } diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/AuxStateChanTypeGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/AuxStateChanTypeGen.java similarity index 95% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/AuxStateChanTypeGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/AuxStateChanTypeGen.java index db62e11cd..8cad5b6d5 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/AuxStateChanTypeGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/AuxStateChanTypeGen.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi; +package org.scribble.codegen.java.statechanapi; import org.scribble.codegen.java.util.TypeBuilder; diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/BranchSockGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/BranchSockGen.java similarity index 84% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/BranchSockGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/BranchSockGen.java index c10e803ed..e5f5aa47b 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/BranchSockGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/BranchSockGen.java @@ -11,28 +11,29 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi; +package org.scribble.codegen.java.statechanapi; import java.util.stream.Collectors; -import org.scribble.ast.DataTypeDecl; -import org.scribble.ast.MessageSigNameDecl; +import org.scribble.ast.DataDecl; +import org.scribble.ast.SigDecl; import org.scribble.ast.Module; -import org.scribble.codegen.java.endpointapi.ioifaces.BranchIfaceGen; -import org.scribble.codegen.java.endpointapi.ioifaces.HandleIfaceGen; -import org.scribble.codegen.java.endpointapi.ioifaces.IOStateIfaceGen; -import org.scribble.codegen.java.endpointapi.ioifaces.SuccessorIfaceGen; +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.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.name.DataType; -import org.scribble.type.name.MessageSigName; -import org.scribble.type.name.PayloadElemType; -import org.scribble.type.name.Role; +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 { @@ -56,7 +57,7 @@ protected void addImports() //private void addBranchMethod(ClassBuilder cb, EndpointState curr) @Override - protected void addMethods() throws ScribbleException + protected void addMethods() throws ScribException { final String ROLE_PARAM = "role"; final String MESSAGE_VAR = "m"; @@ -73,7 +74,7 @@ protected void addMethods() throws ScribbleException //cb.addImports("java.util.concurrent.ExecutionException"); //boolean first; - Role peer = this.curr.getActions().iterator().next().obj; + Role peer = this.curr.getDetActions().iterator().next().obj; // Branch method addBranchMethod(ROLE_PARAM, MESSAGE_VAR, OPENUM_VAR, OP, peer, next, enumClass); @@ -84,7 +85,8 @@ protected void addMethods() throws ScribbleException EnumBuilder eb = cb.newMemberEnum(enumClass); eb.addModifiers(JavaBuilder.PUBLIC); eb.addInterfaces(OPENUM_INTERFACE); - this.curr.getActions().stream().forEach((a) -> eb.addValues(SessionApiGenerator.getOpClassName(a.mid))); + 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 } @@ -104,7 +106,7 @@ private void addBranchMethod(final String ROLE_PARAM, final String MESSAGE_VAR, { MethodBuilder mb = cb.newMethod("branch"); mb.setReturn(next); - mb.addParameters(SessionApiGenerator.getRoleClassName(curr.getActions().iterator().next().obj) + " " + ROLE_PARAM); + 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) @@ -116,7 +118,7 @@ private void addBranchMethod(final String ROLE_PARAM, final String MESSAGE_VAR, + JavaBuilder.SUPER + ".readScribMessage(" + getSessionApiRoleConstant(peer) + ");"); mb.addBodyLine(enumClass + " " + OPENUM_VAR + ";"); boolean first = true; - for (EAction a : this.curr.getActions()) + for (EAction a : this.curr.getDetActions()) { mb.addBodyLine(((first) ? "" : "else ") + "if (" + OP + ".equals(" + getSessionApiOpConstant(a.mid) + ")) {"); mb.addBodyLine(1, OPENUM_VAR + " = " @@ -145,7 +147,7 @@ private String addBranchCallbackMethod(final String ROLE_PARAM, Role peer) mb2.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "IOException", "ClassNotFoundException");//, "ExecutionException", "InterruptedException"); first = true; handleif += "<"; - for (EAction a : this.curr.getActions().stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR).collect(Collectors.toList())) + for (EAction a : this.curr.getDetActions().stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR).collect(Collectors.toList())) { if (first) { @@ -155,7 +157,7 @@ private String addBranchCallbackMethod(final String ROLE_PARAM, Role peer) { handleif += ", "; } - EState succ = this.curr.getSuccessor(a); + EState succ = this.curr.getDetSuccessor(a); if (succ.isTerminal()) { handleif += ScribSockGen.GENERATED_ENDSOCKET_NAME; @@ -249,7 +251,7 @@ private void addHandleMethod(final String ROLE_PARAM, final String MESSAGE_VAR, 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.getActions().stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR) + 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); @@ -259,9 +261,9 @@ private void addHandleMethod(final String ROLE_PARAM, final String MESSAGE_VAR, mb4.addBodyLine(StateChannelApiGenerator.SCRIBMESSAGE_CLASS + " " + MESSAGE_VAR + " = " + JavaBuilder.SUPER + ".readScribMessage(" + getSessionApiRoleConstant(peer) + ");"); first = true; - for (EAction a : this.curr.getActions()) + for (EAction a : this.curr.getDetActions()) { - EState succ = this.curr.getSuccessor(a); + EState succ = this.curr.getDetSuccessor(a); if (first) { first = false; @@ -290,17 +292,17 @@ private void addHandleMethod(final String ROLE_PARAM, final String MESSAGE_VAR, { String buffSuper = JavaBuilder.NEW + " " + BUF_CLASS + "<>("; int i = 0; - for (PayloadElemType pt : a.payload.elems) + for (PayElemType 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++ + "])"; + DataDecl dtd = main.getTypeDeclChild((DataName) pt); // TODO: if not DataType + ln += ", " + buffSuper + "(" + dtd.getExtName() + ") " + 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 + 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 + ")"; } @@ -346,9 +348,9 @@ private void addCallbackCases(MethodBuilder mb2, final String ROLE_PARAM, mb2.addBodyLine(StateChannelApiGenerator.SCRIBMESSAGE_CLASS + " " + MESSAGE_VAR + " = " + JavaBuilder.SUPER + ".readScribMessage(" + getSessionApiRoleConstant(peer) + ");"); first = true; - for (EAction a : this.curr.getActions()) + for (EAction a : this.curr.getDetActions()) { - EState succ = this.curr.getSuccessor(a); + EState succ = this.curr.getDetSuccessor(a); if (first) { first = false; @@ -377,17 +379,17 @@ private void addCallbackCases(MethodBuilder mb2, final String ROLE_PARAM, { String buffSuper = JavaBuilder.NEW + " " + BUF_CLASS + "<>("; int i = 0; - for (PayloadElemType pt : a.payload.elems) + for (PayElemType 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++ + "])"; + DataDecl dtd = main.getTypeDeclChild((DataName) pt); // TODO: if not DataType + ln += ", " + buffSuper + "(" + dtd.getExtName() + ") " + 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 + 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 + ")"; } diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/CaseSockGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/CaseSockGen.java similarity index 84% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/CaseSockGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/CaseSockGen.java index e1802804e..e64c90412 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/CaseSockGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/CaseSockGen.java @@ -11,24 +11,25 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi; +package org.scribble.codegen.java.statechanapi; import java.util.stream.Collectors; -import org.scribble.ast.MessageSigNameDecl; +import org.scribble.ast.SigDecl; import org.scribble.ast.Module; -import org.scribble.codegen.java.endpointapi.ioifaces.BranchIfaceGen; -import org.scribble.codegen.java.endpointapi.ioifaces.IOStateIfaceGen; +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.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.name.DataType; -import org.scribble.type.name.MessageSigName; -import org.scribble.type.name.Role; +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 { @@ -77,7 +78,7 @@ protected MethodBuilder addConstructor() //private String constructCaseClass(EndpointState curr, Module main) @Override - protected void addMethods() throws ScribbleException + 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); @@ -91,12 +92,12 @@ protected void addMethods() throws ScribbleException fb2.addModifiers(JavaBuilder.PRIVATE, JavaBuilder.FINAL); fb2.setType(StateChannelApiGenerator.SCRIBMESSAGE_CLASS); - for (EAction a : this.curr.getActions()) + for (EAction a : this.curr.getDetActions()) { - EState succ = this.curr.getSuccessor(a); + EState succ = this.curr.getDetSuccessor(a); addReceiveMethod(this.cb, a, succ); addCaseReceiveMethod(this.cb, a, succ); - if (!a.payload.isEmpty() || a.mid.isMessageSigName()) + if (!a.payload.isEmpty() || a.mid.isSigName()) { addCaseReceiveDiscardMethod(this.cb, a, succ); } @@ -116,7 +117,7 @@ protected void addMethods() throws ScribbleException } // Same as in ReceiveSocketGenerator - private MethodBuilder makeReceiveHeader(ClassBuilder cb, EAction a, EState succ) throws ScribbleException + private MethodBuilder makeReceiveHeader(ClassBuilder cb, EAction a, EState succ) throws ScribException { MethodBuilder mb = cb.newMethod(); ReceiveSockGen.setReceiveHeaderWithoutReturnType(this.apigen, a, mb); @@ -124,7 +125,7 @@ private MethodBuilder makeReceiveHeader(ClassBuilder cb, EAction a, EState succ) return mb; } - private void addReceiveMethod(ClassBuilder cb, EAction a, EState succ) throws ScribbleException + private void addReceiveMethod(ClassBuilder cb, EAction a, EState succ) throws ScribException { Module main = this.apigen.getMainModule(); @@ -137,15 +138,15 @@ private void addReceiveMethod(ClassBuilder cb, EAction a, EState succ) throws Sc } else //if (a.mid.isMessageSigName()) { - MessageSigNameDecl msd = main.getMessageSigDecl(((MessageSigName) a.mid).getSimpleName()); // FIXME: might not belong to main module + 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.extName + ") " + 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 ScribbleException + private MethodBuilder makeCaseReceiveHeader(ClassBuilder cb, EAction a, EState succ) throws ScribException { MethodBuilder mb = cb.newMethod(); setCaseReceiveHeaderWithoutReturnType(this.apigen, a, mb); @@ -153,7 +154,7 @@ private MethodBuilder makeCaseReceiveHeader(ClassBuilder cb, EAction a, EState s return mb; } - private void addCaseReceiveMethod(ClassBuilder cb, EAction a, EState succ) throws ScribbleException + 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) + ", "; @@ -192,12 +193,12 @@ private void addCaseReceiveDiscardMethod(ClassBuilder cb, EAction a, EState succ if (a.mid.isOp()) { ln += a.payload.elems.stream() - .map((pt) -> getGarbageBuf(main.getDataTypeDecl(((DataType) pt)).extName)).collect(Collectors.joining(", ")) + ");"; + .map((pt) -> getGarbageBuf(main.getTypeDeclChild(((DataName) pt)).getExtName())).collect(Collectors.joining(", ")) + ");"; } else { - MessageSigNameDecl msd = main.getMessageSigDecl(((MessageSigName) a.mid).getSimpleName()); // Factor out? (send/receive/branchreceive/...) - ln += getGarbageBuf(msd.extName) + ");"; + SigDecl msd = main.getSigDeclChild(((SigName) a.mid).getSimpleName()); // Factor out? (send/receive/branchreceive/...) + ln += getGarbageBuf(msd.getExtName()) + ");"; } mb.addBodyLine(ln); } @@ -211,7 +212,7 @@ private static void addBranchCheck(String opClassName, MethodBuilder mb, String } // As for ReceiveSocket, but without peer param - public static void setCaseReceiveHeaderWithoutReturnType(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb) throws ScribbleException + 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? @@ -227,7 +228,7 @@ public static void setCaseReceiveHeaderWithoutReturnType(StateChannelApiGenerato } else //if (a.mid.isMessageSigName()) { - MessageSigNameDecl msd = main.getMessageSigDecl(((MessageSigName) a.mid).getSimpleName()); // FIXME: might not belong to main module + SigDecl msd = main.getSigDeclChild(((SigName) a.mid).getSimpleName()); // FIXME: might not belong to main module ReceiveSockGen.addReceiveMessageSigNameParams(mb, msd, true); } } diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/EndSockGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/EndSockGen.java similarity index 91% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/EndSockGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/EndSockGen.java index 74a7dc069..31efe7e2c 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/EndSockGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/EndSockGen.java @@ -11,9 +11,9 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi; +package org.scribble.codegen.java.statechanapi; -import org.scribble.model.endpoint.EState; +import org.scribble.core.model.endpoint.EState; public class EndSockGen extends ScribSockGen { diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/HandlerIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/HandlerIfaceGen.java similarity index 82% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/HandlerIfaceGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/HandlerIfaceGen.java index ff1357ce5..6407e0702 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/HandlerIfaceGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/HandlerIfaceGen.java @@ -11,20 +11,21 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi; +package org.scribble.codegen.java.statechanapi; -import org.scribble.ast.MessageSigNameDecl; +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.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.MessageSigName; +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 @@ -39,9 +40,9 @@ public HandlerIfaceGen(StateChannelApiGenerator apigen, ClassBuilder parent, ESt } @Override - public InterfaceBuilder generateType() throws ScribbleException + public InterfaceBuilder generateType() throws ScribException { - GProtocolName gpn = this.apigen.getGProtocolName(); + GProtoName gpn = this.apigen.getGProtocolName(); // Handler interface InterfaceBuilder ib = new InterfaceBuilder(); @@ -51,9 +52,9 @@ public InterfaceBuilder generateType() throws ScribbleException ib.setName(getHandlerInterfaceName(this.parent.getName())); ib.addModifiers(InterfaceBuilder.PUBLIC); - for (EAction a : this.curr.getActions()) // Doesn't need to be sorted + for (EAction a : this.curr.getDetActions()) // Doesn't need to be sorted { - EState succ = this.curr.getSuccessor(a); + EState succ = this.curr.getDetSuccessor(a); String nextClass = this.apigen.getSocketClassName(succ); AbstractMethodBuilder mb3 = ib.newAbstractMethod(); @@ -72,7 +73,7 @@ public InterfaceBuilder generateType() throws ScribbleException } addHandleMethodOpAndPayloadParams(this.apigen, a, mb3); - if (this.curr.getSuccessor(a).isTerminal()) + if (this.curr.getDetSuccessor(a).isTerminal()) { // FIXME: potentially repeated (but OK) ib.addImports(SessionApiGenerator.getEndpointApiRootPackageName(gpn) + ".*"); // FIXME: factor out with ScribSocketBuilder @@ -92,7 +93,7 @@ public static void setHandleMethodHeaderWithoutParamTypes(StateChannelApiGenerat mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "java.io.IOException", "ClassNotFoundException"); } - public static void addHandleMethodOpAndPayloadParams(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb) throws ScribbleException + public static void addHandleMethodOpAndPayloadParams(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb) throws ScribException { Module main = apigen.getMainModule(); String opClass = SessionApiGenerator.getOpClassName(a.mid); @@ -105,7 +106,7 @@ public static void addHandleMethodOpAndPayloadParams(StateChannelApiGenerator ap } else //if (a.mid.isMessageSigName()) { - MessageSigNameDecl msd = main.getMessageSigDecl(((MessageSigName) a.mid).getSimpleName()); // FIXME: might not belong to main module + SigDecl msd = main.getSigDeclChild(((SigName) a.mid).getSimpleName()); // FIXME: might not belong to main module ReceiveSockGen.addReceiveMessageSigNameParams(mb, msd, false); } } diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/InputFutureGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/InputFutureGen.java similarity index 80% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/InputFutureGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/InputFutureGen.java index 26ff607e5..222729a0b 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/InputFutureGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/InputFutureGen.java @@ -11,30 +11,31 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi; +package org.scribble.codegen.java.statechanapi; import java.util.LinkedList; import java.util.List; -import org.scribble.ast.DataTypeDecl; -import org.scribble.ast.MessageSigNameDecl; +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.main.ScribbleException; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.name.DataType; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.MessageSigName; -import org.scribble.type.name.PayloadElemType; +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.net.ScribFuture"; + protected static final String SCRIBFUTURE_CLASS = "org.scribble.runtime.util.ScribFuture"; private final EAction a; @@ -46,11 +47,11 @@ public InputFutureGen(StateChannelApiGenerator apigen, ClassBuilder parent, EAct } @Override - public ClassBuilder generateType() throws ScribbleException + public ClassBuilder generateType() throws ScribException { final String FUTURE_PARAM = "fut"; Module main = this.apigen.getMainModule(); - GProtocolName gpn = this.apigen.getGProtocolName(); + GProtoName gpn = this.apigen.getGProtocolName(); String futureClass = getInputFutureName(this.parent.getName()); // Fresh enough? need only one future class per receive (unary receive) @@ -73,15 +74,15 @@ public ClassBuilder generateType() throws ScribbleException if (!a.payload.isEmpty()) { int i = 1; - for (PayloadElemType pt : a.payload.elems) + for (PayElemType pt : a.payload.elems) { - if (!pt.isDataType()) + if (!pt.isDataName()) { - throw new ScribbleException("[TODO] API generation not supported for non- data type payloads: " + pt); + throw new ScribException("[TODO] API generation not supported for non- data type payloads: " + pt); } - DataTypeDecl dtd = main.getDataTypeDecl((DataType) pt); + DataDecl dtd = main.getTypeDeclChild((DataName) pt); ScribSockGen.checkJavaDataTypeDecl(dtd); - String type = dtd.extName; + String type = dtd.getExtName(); types.add(type); FieldBuilder f = future.newField("pay" + i++); f.setType(type); @@ -91,9 +92,9 @@ public ClassBuilder generateType() throws ScribbleException } else { - MessageSigNameDecl msd = main.getMessageSigDecl(((MessageSigName) a.mid).getSimpleName()); + SigDecl msd = main.getSigDeclChild(((SigName) a.mid).getSimpleName()); ScribSockGen.checkMessageSigNameDecl(msd); - String type = msd.extName; + String type = msd.getExtName(); types.add(type); FieldBuilder f = future.newField("msg"); f.setType(type); diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/OutputSockGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/OutputSockGen.java similarity index 79% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/OutputSockGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/OutputSockGen.java index 31dec434d..ccd3af9cc 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/OutputSockGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/OutputSockGen.java @@ -11,24 +11,25 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi; +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.DataTypeDecl; -import org.scribble.ast.MessageSigNameDecl; +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.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.name.DataType; -import org.scribble.type.name.MessageSigName; -import org.scribble.type.name.PayloadElemType; +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 { @@ -53,16 +54,16 @@ protected void addImports() // A method for each successor state //private void addSendMethods(ClassBuilder cb, EndpointState curr) @Override - protected void addMethods() throws ScribbleException + protected void addMethods() throws ScribException { final String ROLE_PARAM = "role"; // Mixed sends and connects boolean hasConnect = false; boolean hasWrap = false; - for (EAction a : curr.getActions()) // (Scribble ensures all "a" are input or all are output) + for (EAction a : curr.getDetActions()) // (Scribble ensures all "a" are input or all are output) { - EState succ = curr.getSuccessor(a); + EState succ = curr.getDetSuccessor(a); MethodBuilder mb = this.cb.newMethod(); if (a.isSend()) @@ -78,7 +79,7 @@ else if (a.isDisconnect()) { setDisconnectHeaderWithoutReturnType(apigen, a, mb); } - else if (a.isWrapClient()) + else if (a.isClientWrap()) { hasWrap = true; setWrapClientHeaderWithoutReturnType(apigen, a, mb); @@ -123,7 +124,7 @@ else if (a.isDisconnect()) { mb.addBodyLine(JavaBuilder.SUPER + ".disconnect(" + ROLE_PARAM + ");\n"); } - else if (a.isWrapClient()) + else if (a.isClientWrap()) { mb.addBodyLine(JavaBuilder.SUPER + ".wrapClient(" + ROLE_PARAM + ", wrapper);\n"); } @@ -138,12 +139,12 @@ else if (a.isWrapClient()) if (hasConnect) { this.cb.addImports("java.util.concurrent.Callable"); - this.cb.addImports("org.scribble.runtime.net.session.BinaryChannelEndpoint"); + this.cb.addImports("org.scribble.runtime.net.BinaryChannelEndpoint"); } if (hasWrap) { this.cb.addImports("java.util.concurrent.Callable"); - this.cb.addImports("org.scribble.runtime.net.session.BinaryChannelWrapper"); + this.cb.addImports("org.scribble.runtime.net.BinaryChannelWrapper"); } } @@ -154,7 +155,7 @@ private static List getSendPayloadArgs(EAction a) 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 ScribbleException + 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? @@ -169,7 +170,7 @@ public static void setSendHeaderWithoutReturnType(StateChannelApiGenerator apige } else //if (a.mid.isMessageSigName()) { - MessageSigNameDecl msd = main.getMessageSigDecl(((MessageSigName) a.mid).getSimpleName()); // FIXME: might not belong to main module + SigDecl msd = main.getSigDeclChild(((SigName) a.mid).getSimpleName()); // FIXME: might not belong to main module addSendMessageSigNameParams(mb, msd); } } @@ -178,7 +179,7 @@ public static void setConnectHeaderWithoutReturnType(StateChannelApiGenerator ap { final String ROLE_PARAM = "role"; - mb.setName("connect"); + 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 @@ -208,31 +209,31 @@ public static void setWrapClientHeaderWithoutReturnType(StateChannelApiGenerator mb.addParameters("Callable wrapper"); } - protected static void addSendOpParams(StateChannelApiGenerator apigen, MethodBuilder mb, Module main, EAction a) throws ScribbleException + 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 (PayloadElemType pt : a.payload.elems) + for (PayElemType pt : a.payload.elems) { - if (!pt.isDataType()) + if (!pt.isDataName()) { - throw new ScribbleException("[TODO] API generation not supported for non- data type payloads: " + pt); + throw new ScribException("[TODO] API generation not supported for non- data type payloads: " + pt); } - DataTypeDecl dtd = main.getDataTypeDecl((DataType) pt); // FIXME: might not belong to main module // TODO: if not DataType + DataDecl dtd = main.getTypeDeclChild((DataName) pt); // FIXME: might not belong to main module // TODO: if not DataType ScribSockGen.checkJavaDataTypeDecl(dtd); - mb.addParameters(dtd.extName + " " + as.next()); + mb.addParameters(dtd.getExtName() + " " + as.next()); } } } - protected static void addSendMessageSigNameParams(MethodBuilder mb, MessageSigNameDecl msd) throws ScribbleException + protected static void addSendMessageSigNameParams(MethodBuilder mb, SigDecl msd) throws ScribException { final String MESSAGE_PARAM = "m"; ScribSockGen.checkMessageSigNameDecl(msd); - mb.addParameters(msd.extName + " " + MESSAGE_PARAM); + mb.addParameters(msd.getExtName() + " " + MESSAGE_PARAM); } } diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ReceiveSockGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ReceiveSockGen.java similarity index 83% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ReceiveSockGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ReceiveSockGen.java index 99e645e3d..19273b0ac 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ReceiveSockGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ReceiveSockGen.java @@ -11,20 +11,21 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi; +package org.scribble.codegen.java.statechanapi; -import org.scribble.ast.DataTypeDecl; -import org.scribble.ast.MessageSigNameDecl; +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.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.name.DataType; -import org.scribble.type.name.MessageSigName; -import org.scribble.type.name.PayloadElemType; +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 { @@ -51,11 +52,11 @@ protected void addImports() // 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 ScribbleException + protected void addMethods() throws ScribException { - EAction a = curr.getActions().iterator().next(); + EAction a = curr.getDetActions().iterator().next(); //String nextClass = this.apigen.getSocketClassName(curr.accept(a)); - EState succ = curr.getSuccessor(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); @@ -68,7 +69,7 @@ protected void addMethods() throws ScribbleException // [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 ScribbleException + private void makeReceiveMethod(EAction a, EState succ) throws ScribException { Module main = this.apigen.getMainModule(); // FIXME: main not necessarily the right module? @@ -83,17 +84,17 @@ private void makeReceiveMethod(EAction a, EState succ) throws ScribbleException } else //if (a.mid.isMessageSigName()) { - MessageSigNameDecl msd = main.getMessageSigDecl(((MessageSigName) a.mid).getSimpleName()); // FIXME: might not belong to main module + 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.extName + ") " + RECEIVE_MESSAGE_PARAM + ";"); + 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 ScribbleException + private MethodBuilder makeReceiveHeader(EAction a, EState succ) throws ScribException { MethodBuilder mb = this.cb.newMethod(); setReceiveHeaderWithoutReturnType(this.apigen, a, mb); @@ -150,7 +151,7 @@ private void makeIsDoneMethod(EAction a) // 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 ScribbleException + 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? @@ -167,27 +168,27 @@ public static void setReceiveHeaderWithoutReturnType(StateChannelApiGenerator ap } else //if (a.mid.isMessageSigName()) { - MessageSigNameDecl msd = main.getMessageSigDecl(((MessageSigName) a.mid).getSimpleName()); // FIXME: might not belong to main module + 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 ScribbleException + 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 (PayloadElemType pt : a.payload.elems) + for (PayElemType pt : a.payload.elems) { - if (!pt.isDataType()) + if (!pt.isDataName()) { - throw new ScribbleException("[TODO] API generation not supported for non- data type payloads: " + pt); + throw new ScribException("[TODO] API generation not supported for non- data type payloads: " + pt); } - DataTypeDecl dtd = main.getDataTypeDecl((DataType) pt); // TODO: if not DataType + DataDecl dtd = main.getTypeDeclChild((DataName) pt); // TODO: if not DataType ScribSockGen.checkJavaDataTypeDecl(dtd); - mb.addParameters(buffSuper + dtd.extName + "> " + RECEIVE_ARG_PREFIX + i++); + mb.addParameters(buffSuper + dtd.getExtName() + "> " + RECEIVE_ARG_PREFIX + i++); } } } @@ -197,19 +198,19 @@ protected static void addPayloadBuffSetters(Module main, EAction a, MethodBuilde if (!a.payload.isEmpty()) { int i = 1; - for (PayloadElemType pt : a.payload.elems) // Could factor out this loop (arg names) with addReceiveOpParams (as for send) + for (PayElemType pt : a.payload.elems) // Could factor out this loop (arg names) with addReceiveOpParams (as for send) { - DataTypeDecl dtd = main.getDataTypeDecl((DataType) pt); // TODO: if not DataType - mb.addBodyLine(RECEIVE_ARG_PREFIX + i + "." + BUFF_VAL_FIELD + " = (" + dtd.extName + ") " + 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, MessageSigNameDecl msd, boolean superr) throws ScribbleException + protected static void addReceiveMessageSigNameParams(MethodBuilder mb, SigDecl msd, boolean superr) throws ScribException { ScribSockGen.checkMessageSigNameDecl(msd); - mb.addParameters(BUF_CLASS + "<" + ((superr) ? "? " + JavaBuilder.SUPER + " " : "") + msd.extName + "> " + RECEIVE_ARG_PREFIX); + mb.addParameters(BUF_CLASS + "<" + ((superr) ? "? " + JavaBuilder.SUPER + " " : "") + msd.getExtName() + "> " + RECEIVE_ARG_PREFIX); } // Similar to setReceiveHeader diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ScribSockGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ScribSockGen.java similarity index 83% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ScribSockGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ScribSockGen.java index d98a04023..1321f20fd 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ScribSockGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ScribSockGen.java @@ -11,44 +11,46 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi; +package org.scribble.codegen.java.statechanapi; -import org.scribble.ast.DataTypeDecl; -import org.scribble.ast.MessageSigNameDecl; -import org.scribble.ast.NonProtocolDecl; -import org.scribble.ast.global.GProtocolDecl; +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.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; +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.net.session.SessionEndpoint"; - public static final String MPSTENDPOINT_CLASS = "org.scribble.runtime.net.session.MPSTEndpoint"; - public static final String EXPLICITENDPOINT_CLASS = "org.scribble.runtime.net.session.ExplicitEndpoint"; - public static final String BUF_CLASS = "org.scribble.runtime.net.Buf"; - public static final String OPENUM_INTERFACE = "org.scribble.runtime.net.session.OpEnum"; + 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 CONNECTSOCKET_CLASS = "org.scribble.net.scribsock.ConnectSocket"; - public static final String ACCEPTSOCKET_CLASS = "org.scribble.runtime.net.scribsock.AcceptSocket"; - //public static final String DISCONNECTSOCKET_CLASS = "org.scribble.net.scribsock.DisconnectSocket"; - public static final String OUTPUTSOCKET_CLASS = "org.scribble.runtime.net.scribsock.OutputSocket"; - public static final String RECEIVESOCKET_CLASS = "org.scribble.runtime.net.scribsock.ReceiveSocket"; - public static final String BRANCHSOCKET_CLASS = "org.scribble.runtime.net.scribsock.BranchSocket"; - public static final String CASESOCKET_CLASS = "org.scribble.runtime.net.scribsock.CaseSocket"; - public static final String ENDSOCKET_CLASS = "org.scribble.runtime.net.scribsock.EndSocket"; + public static final String BUF_CLASS = "org.scribble.runtime.util.Buf"; - public static final String SCRIBSERVERSOCKET_CLASS = "org.scribble.runtime.net.scribsock.ScribServerSocket"; + //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"; @@ -83,13 +85,13 @@ protected String getClassName() } @Override - public ClassBuilder generateType() throws ScribbleException + public ClassBuilder generateType() throws ScribException { constructClass(); // So className can be "overridden" in subclass constructor (CaseSocket) return this.cb; } - protected void constructClass() throws ScribbleException + protected void constructClass() throws ScribException { constructClassExceptMethods(); addMethods(); @@ -151,9 +153,13 @@ protected void addInitialStateConstructor() mb.addBodyLine(SESSIONENDPOINT_PARAM + ".init();"); mb.addBodyLine(ClassBuilder.RETURN + " " + ClassBuilder.NEW + " " + this.root + "(" + SESSIONENDPOINT_PARAM + ");");*/ - GProtocolDecl gpd = (GProtocolDecl) this.apigen.getJob().getContext().getModule(this.apigen.gpn.getPrefix()).getProtocolDecl(this.apigen.gpn.getSimpleName()); - String epClass = gpd.isExplicitModifier() ? EXPLICITENDPOINT_CLASS : MPSTENDPOINT_CLASS; - ConstructorBuilder ctor2 = cb.newConstructor(epClass + "<" + sess + ", " + role + "> " + 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); @@ -161,7 +167,7 @@ protected void addInitialStateConstructor() ctor2.addBodyLine(SESSIONENDPOINT_PARAM + ".init();"); } - protected abstract void addMethods() throws ScribbleException; + protected abstract void addMethods() throws ScribException; /*@Deprecated protected void setNextSocketReturnType(MethodBuilder mb, EState succ) @@ -201,7 +207,7 @@ protected String getSessionApiRoleConstant(Role 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(MessageId mid) + protected String getSessionApiOpConstant(MsgId mid) { return SessionApiGenerator.getSessionClassName(this.apigen.getGProtocolName()) + "." + SessionApiGenerator.getOpClassName(mid); } @@ -245,7 +251,7 @@ public static void setNextSocketReturnType(StateChannelApiGenerator apigen, Meth String ret; if (succ.isTerminal()) { - GProtocolName gpn = apigen.getGProtocolName(); + GProtoName gpn = apigen.getGProtocolName(); Role self = apigen.getSelf(); ret = SessionApiGenerator.getStateChannelPackageName(gpn, self) + "." + GENERATED_ENDSOCKET_NAME; //+ "<" + SessionApiGenerator.getSessionClassName(gpn) + ", " + SessionApiGenerator.getRoleClassName(self) + ">"; @@ -257,21 +263,21 @@ public static void setNextSocketReturnType(StateChannelApiGenerator apigen, Meth mb.setReturn(ret); } - protected static void checkJavaDataTypeDecl(DataTypeDecl dtd) throws ScribbleException + protected static void checkJavaDataTypeDecl(DataDecl dtd) throws ScribException { checkJavaSchema(dtd); } - protected static void checkMessageSigNameDecl(MessageSigNameDecl msd) throws ScribbleException + protected static void checkMessageSigNameDecl(SigDecl msd) throws ScribException { checkJavaSchema(msd); } - protected static void checkJavaSchema(NonProtocolDecl npd) throws ScribbleException + protected static void checkJavaSchema(NonProtoDecl npd) throws ScribException { - if (!npd.schema.equals(ScribSockGen.JAVA_SCHEMA)) // FIXME: factor out + if (!npd.getSchema().equals(ScribSockGen.JAVA_SCHEMA)) // FIXME: factor out { - throw new ScribbleException(npd.getSource(), "Unsupported data type schema: " + npd.schema); + throw new ScribException(npd.getSource(), "Unsupported data type schema: " + npd.getSchema()); } } diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/StateChanTypeGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/StateChanTypeGen.java similarity index 82% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/StateChanTypeGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/StateChanTypeGen.java index 07b6a556d..1c6ac3777 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/StateChanTypeGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/StateChanTypeGen.java @@ -11,10 +11,10 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi; +package org.scribble.codegen.java.statechanapi; import org.scribble.codegen.java.util.TypeBuilder; -import org.scribble.main.ScribbleException; +import org.scribble.util.ScribException; // Build a (top-level) type declaration for the API generation output public abstract class StateChanTypeGen @@ -26,5 +26,5 @@ public StateChanTypeGen(StateChannelApiGenerator apigen) this.apigen = apigen; } - public abstract TypeBuilder generateType() throws ScribbleException; // FIXME: APIGenerationException? + 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/endpointapi/ioifaces/ActionIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/ActionIfaceGen.java similarity index 82% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/ActionIfaceGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/ActionIfaceGen.java index d1ff9f4e9..c256808a8 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/ActionIfaceGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/ActionIfaceGen.java @@ -11,21 +11,21 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi.ioifaces; +package org.scribble.codegen.java.statechanapi.ioifaces; -import org.scribble.codegen.java.endpointapi.ReceiveSockGen; -import org.scribble.codegen.java.endpointapi.OutputSockGen; -import org.scribble.codegen.java.endpointapi.SessionApiGenerator; -import org.scribble.codegen.java.endpointapi.StateChannelApiGenerator; +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.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.model.endpoint.actions.EReceive; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.PayloadElemType; +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 { @@ -39,9 +39,9 @@ public ActionIfaceGen(StateChannelApiGenerator apigen, EState curr, EAction a) } @Override - public InterfaceBuilder generateType() throws ScribbleException + public InterfaceBuilder generateType() throws ScribException { - GProtocolName gpn = this.apigen.getGProtocolName(); + GProtoName gpn = this.apigen.getGProtocolName(); this.ib.setName(getActionInterfaceName(this.a)); this.ib.setPackage(IOInterfacesGenerator.getIOInterfacePackageName(this.apigen.getGProtocolName(), this.apigen.getSelf())); @@ -53,7 +53,7 @@ public InterfaceBuilder generateType() throws ScribbleException 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 EReceive) + if (this.a instanceof ERecv) { /*if (this.curr.getAcceptable().size() > 1) { @@ -107,7 +107,7 @@ public static String getActionInterfaceName(EAction a) : "Out";*/ String name; //if (curr.getAcceptable().iterator().next() instanceof Receive) - if (a instanceof EReceive) + if (a instanceof ERecv) { /*if (curr.getAcceptable().size() > 1) { @@ -130,7 +130,7 @@ public static String getActionString(EAction a) // FIXME: peer not needed for i { //String name = a.peer + "$" + a.mid; String name = a.obj + "_" + a.mid; - for (PayloadElemType pay : a.payload.elems) + for (PayElemType pay : a.payload.elems) { //name += "$" + pay; name += "_" + pay; diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/BranchIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/BranchIfaceGen.java similarity index 83% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/BranchIfaceGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/BranchIfaceGen.java index 9eeb97be4..90c0f47c9 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/BranchIfaceGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/BranchIfaceGen.java @@ -11,24 +11,24 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi.ioifaces; +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.endpointapi.ScribSockGen; -import org.scribble.codegen.java.endpointapi.SessionApiGenerator; -import org.scribble.codegen.java.endpointapi.StateChannelApiGenerator; +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.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.name.Role; +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 { @@ -38,7 +38,7 @@ public BranchIfaceGen(StateChannelApiGenerator apigen, Map as = this.curr.getActions(); - List as = this.curr.getActions(); + List as = this.curr.getDetActions(); // FIXME: factor out with BranchSocketGenerator AbstractMethodBuilder bra = this.ib.newAbstractMethod("branch"); @@ -84,7 +84,8 @@ protected void addBranchEnum() EnumBuilder eb = this.ib.newMemberEnum(getBranchInterfaceEnumName(self, this.curr)); eb.addModifiers(JavaBuilder.PUBLIC); eb.addInterfaces(ScribSockGen.OPENUM_INTERFACE); - this.curr.getActions().stream().forEach((a) -> eb.addValues(SessionApiGenerator.getOpClassName(a.mid))); + this.curr.getDetActions() + .forEach(a -> eb.addValues(SessionApiGenerator.getOpClassName(a.mid))); } // Don't add Action Interfaces (added to CaseInterface) @@ -92,7 +93,7 @@ protected void addBranchEnum() protected void addSuccessorParamsAndActionInterfaces() { int i = 1; - for (EAction a : this.curr.getActions().stream().sorted(IOACTION_COMPARATOR).collect(Collectors.toList())) + for (EAction a : this.curr.getDetActions().stream().sorted(IOACTION_COMPARATOR).collect(Collectors.toList())) { this.ib.addParameters("__Succ" + i + " extends " + SuccessorIfaceGen.getSuccessorInterfaceName(a)); i++; diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/CaseIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/CaseIfaceGen.java similarity index 76% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/CaseIfaceGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/CaseIfaceGen.java index 846be4c29..4d22aca14 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/CaseIfaceGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/CaseIfaceGen.java @@ -11,25 +11,25 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi.ioifaces; +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.endpointapi.CaseSockGen; -import org.scribble.codegen.java.endpointapi.ScribSockGen; -import org.scribble.codegen.java.endpointapi.SessionApiGenerator; -import org.scribble.codegen.java.endpointapi.StateChannelApiGenerator; +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.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.Role; +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 { @@ -39,7 +39,7 @@ public CaseIfaceGen(StateChannelApiGenerator apigen, Map as = this.curr.getActions(); - List as = this.curr.getActions(); + List as = this.curr.getDetActions(); int i = 1; this.ib.addImports(SessionApiGenerator.getOpsPackageName(gpn) + ".*"); @@ -86,7 +86,7 @@ protected void addCaseReceiveDiscardMethods() { MethodBuilder mb = this.ib.newAbstractMethod(); CaseSockGen.setCaseReceiveDiscardHeaderWithoutReturnType(this.apigen, a, mb); - EState succ = this.curr.getSuccessor(a); + EState succ = this.curr.getDetSuccessor(a); if (succ.isTerminal()) { ScribSockGen.setNextSocketReturnType(this.apigen, mb, succ); @@ -105,7 +105,7 @@ protected void addCaseReceiveDiscardMethods() protected static String getCasesInterfaceName(Role self, EState s) { //return "Case_" + braif.substring("Branch_".length(), braif.length()); - return "Case_" + self + "_" + s.getActions().stream().sorted(IOACTION_COMPARATOR) + 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/endpointapi/ioifaces/HandleIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/HandleIfaceGen.java similarity index 85% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/HandleIfaceGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/HandleIfaceGen.java index 3d0a2b5b3..e84fb1266 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/HandleIfaceGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/HandleIfaceGen.java @@ -11,23 +11,23 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi.ioifaces; +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.endpointapi.HandlerIfaceGen; -import org.scribble.codegen.java.endpointapi.ScribSockGen; -import org.scribble.codegen.java.endpointapi.SessionApiGenerator; +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.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.Role; +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 @@ -45,7 +45,7 @@ public HandleIfaceGen(IOInterfacesGenerator iogen, Map"); @@ -114,12 +114,12 @@ private static List getHandleInterfaceIOActionParams(EndpointState cur return as; }*/ - protected void addHandleMethods() throws ScribbleException + protected void addHandleMethods() throws ScribException { - GProtocolName gpn = this.apigen.getGProtocolName(); + GProtoName gpn = this.apigen.getGProtocolName(); //Role self = this.apigen.getSelf(); //Set as = this.curr.getActions(); - List as = this.curr.getActions(); + List as = this.curr.getDetActions(); this.ib.addImports(SessionApiGenerator.getOpsPackageName(gpn) + ".*"); int i = 1; @@ -173,7 +173,7 @@ protected static void setHandleMethodSuccessorParam(IOInterfacesGenerator iogen, //Map ount = new HashMap<>(); boolean first = true; - for (EAction a : succ.getActions().stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR).collect(Collectors.toList())) + for (EAction a : succ.getDetActions().stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR).collect(Collectors.toList())) { int offset; if (!count.containsKey(a)) @@ -206,7 +206,7 @@ protected static void setHandleMethodSuccessorParam(IOInterfacesGenerator iogen, public static String getHandleInterfaceName(Role self, EState s) { // FIXME: factor out (CaseInterfaceGenerator, IOStateInterfaceGenerator.getIOStateInterfaceName) - String name = "Handle_" + self + "_" + s.getActions().stream().sorted(IOACTION_COMPARATOR) + 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/endpointapi/ioifaces/IOIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOIfaceGen.java similarity index 76% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/IOIfaceGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOIfaceGen.java index 527b61ce6..b7692af9a 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/IOIfaceGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOIfaceGen.java @@ -11,11 +11,11 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi.ioifaces; +package org.scribble.codegen.java.statechanapi.ioifaces; -import org.scribble.codegen.java.endpointapi.StateChannelApiGenerator; -import org.scribble.codegen.java.endpointapi.StateChanTypeGen; -import org.scribble.model.endpoint.EState; +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 { diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/IOInterfacesGenerator.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOInterfacesGenerator.java similarity index 89% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/IOInterfacesGenerator.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOInterfacesGenerator.java index 8bbe7007f..2aec10116 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/IOInterfacesGenerator.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOInterfacesGenerator.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi.ioifaces; +package org.scribble.codegen.java.statechanapi.ioifaces; import java.util.HashMap; import java.util.HashSet; @@ -24,12 +24,12 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; -import org.scribble.codegen.java.endpointapi.ApiGen; -import org.scribble.codegen.java.endpointapi.CaseSockGen; -import org.scribble.codegen.java.endpointapi.HandlerIfaceGen; -import org.scribble.codegen.java.endpointapi.ScribSockGen; -import org.scribble.codegen.java.endpointapi.SessionApiGenerator; -import org.scribble.codegen.java.endpointapi.StateChannelApiGenerator; +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; @@ -37,19 +37,21 @@ import org.scribble.codegen.java.util.JavaBuilder; import org.scribble.codegen.java.util.MethodBuilder; import org.scribble.codegen.java.util.TypeBuilder; -import org.scribble.main.JobContext; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.EStateKind; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.Role; +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; @@ -69,25 +71,30 @@ public class IOInterfacesGenerator extends ApiGen //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 RuntimeScribbleException, ScribbleException + public IOInterfacesGenerator(StateChannelApiGenerator apigen, + boolean subtypes) throws RuntimeScribException, ScribException { super(apigen.getJob(), apigen.getGProtocolName()); this.apigen = apigen; this.SUBTYPES = subtypes; - GProtocolName fullname = apigen.getGProtocolName(); + GProtoName fullname = apigen.getGProtocolName(); Role self = getSelf(); //EndpointState init = this.job.getContext().getEndpointGraph(fullname, self).init; - JobContext jc = this.job.getContext(); - EState init = this.job.minEfsm ? jc.getMinimisedEGraph(fullname, self).init : jc.getEGraph(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 = EState.getReachableActions(init); - if (as.stream().anyMatch((a) -> !a.isSend() && !a.isReceive())) // HACK FIXME (connect/disconnect) + Set as = init.getReachableActions(); + if (as.stream().anyMatch(a -> !a.isSend() && !a.isReceive())) // HACK FIXME (connect/disconnect) { - throw new RuntimeScribbleException("[TODO] I/O Interface generation not supported for: " + as.stream().filter((a) -> !a.isSend() && !a.isReceive()).collect(Collectors.toList())); + throw new RuntimeScribException( + "[TODO] I/O Interface generation not supported for: " + + as.stream().filter(a -> !a.isSend() && !a.isReceive()) + .collect(Collectors.toList())); } } @@ -96,7 +103,7 @@ public IOInterfacesGenerator(StateChannelApiGenerator apigen, boolean subtypes) collectPreds(); //EndpointState term = EndpointState.findTerminalState(new HashSet<>(), init); - EState term = EState.getTerminal(init); + EState term = init.getTerminal(); ClassBuilder endsock = null; if (term != null) { @@ -142,13 +149,13 @@ public IOInterfacesGenerator(StateChannelApiGenerator apigen, boolean subtypes) // 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 RuntimeScribbleException(\"Invalid cast of EndSocket: \" + cast);"); + 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.main.RuntimeScribbleException"); + endsock.addImports("org.scribble.util.RuntimeScribException"); } } } @@ -183,17 +190,21 @@ public Map generateApi() { Map output = new HashMap<>(); String prefix = getIOInterfacePackageName(this.gpn, getSelf()).replace('.', '/') + "/"; - this.actions.values().stream().forEach((ib) -> output.put(prefix + ib.getName() + ".java", ib.build())); - this.succs.values().stream().forEach((ib) -> output.put(prefix + ib.getName() + ".java", ib.build())); - this.iostates.values().stream().forEach((tb) -> output.put(prefix + tb.getName() + ".java", tb.build())); + 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().stream().forEach((ib) -> output.put(prefix + ib.getName() + ".java", ib.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 ScribbleException + private void generateActionAndSuccessorInterfacesAndCollectPreActions(Set visited, EState s) throws ScribException { if (visited.contains(s) || s.isTerminal()) { @@ -202,12 +213,12 @@ private void generateActionAndSuccessorInterfacesAndCollectPreActions(Set as = s.getActions(); - List 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 RuntimeException("TODO: " + a); + throw new RuntimeScribException("TODO: " + a); } if (!this.actions.containsKey(a)) @@ -215,7 +226,7 @@ private void generateActionAndSuccessorInterfacesAndCollectPreActions(Set visited, EState s) throws ScribbleException + private void generateIOStateInterfacesFirstPass(Set visited, EState s) throws ScribException { if (visited.contains(s) || s.isTerminal()) { @@ -273,10 +284,10 @@ private void generateIOStateInterfacesFirstPass(Set visited, EState s) t case OUTPUT: // Send, connect, disconnect ifgen = new SelectIfaceGen(this.apigen, this.actions, s); break; - case UNARY_INPUT: + case UNARY_RECEIVE: ifgen = new ReceiveIfaceGen(this.apigen, this.actions, s); break; - case POLY_INPUT: + 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); @@ -289,9 +300,9 @@ private void generateIOStateInterfacesFirstPass(Set visited, EState s) t } visited.add(s); - for (EAction a : s.getActions()) + for (EAction a : s.getDetActions()) { - generateIOStateInterfacesFirstPass(visited, s.getSuccessor(a)); + generateIOStateInterfacesFirstPass(visited, s.getDetSuccessor(a)); } } @@ -343,20 +354,20 @@ private void generateIOStateInterfacesSecondPass(Set visited, EState s) } visited.add(s); - for (EAction a : s.getActions()) + for (EAction a : s.getDetActions()) { - generateIOStateInterfacesSecondPass(visited, s.getSuccessor(a)); + generateIOStateInterfacesSecondPass(visited, s.getDetSuccessor(a)); } } - private void generateHandleInterfaces(Set visited, EState s) throws ScribbleException + private void generateHandleInterfaces(Set visited, EState s) throws ScribException { if (visited.contains(s) || s.isTerminal()) { return; } - if (s.getStateKind() == EStateKind.POLY_INPUT) + if (s.getStateKind() == EStateKind.POLY_RECIEVE) { //Set succifs = this.preds.get(s); String key = HandleIfaceGen.getHandleInterfaceName(getSelf(), s); @@ -368,9 +379,9 @@ private void generateHandleInterfaces(Set visited, EState s) throws Scri } visited.add(s); - for (EAction a : s.getActions()) + for (EAction a : s.getDetActions()) { - generateHandleInterfaces(visited, s.getSuccessor(a)); + generateHandleInterfaces(visited, s.getDetSuccessor(a)); } } @@ -381,7 +392,7 @@ private void generateHandleInterfacesSecondPass(Set visited, EState s) return; } - if (s.getStateKind() == EStateKind.POLY_INPUT) + if (s.getStateKind() == EStateKind.POLY_RECIEVE) { //GProtocolName gpn = this.apigen.getGProtocolName(); Role self = this.apigen.getSelf(); @@ -442,9 +453,9 @@ private void generateHandleInterfacesSecondPass(Set visited, EState s) } visited.add(s); - for (EAction a : s.getActions()) + for (EAction a : s.getDetActions()) { - generateHandleInterfacesSecondPass(visited, s.getSuccessor(a)); + generateHandleInterfacesSecondPass(visited, s.getDetSuccessor(a)); } } @@ -474,7 +485,7 @@ private void addIOStateInterfacesToStateChannels(Set visited, EState s) iostate.addImports(SessionApiGenerator.getStateChannelPackageName(this.gpn, self) + ".*"); } - if (s.getStateKind() == EStateKind.POLY_INPUT) + if (s.getStateKind() == EStateKind.POLY_RECIEVE) { // Add CaseInterface to each CaseSocket TypeBuilder cases = this.apigen.getType(CaseSockGen.getCaseSocketName(this.apigen.getSocketClassName(s))); @@ -518,7 +529,7 @@ private void addIOStateInterfacesToStateChannels(Set visited, EState s) System.out.println("BBB: " + handle);*/ //for (IOAction a : this.branchSuccs.get(handle)) // FIXME: move back into HandlerInterfaceGenerator - for (EAction a : s.getActions().stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR).collect(Collectors.toList())) + for (EAction a : s.getDetActions().stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR).collect(Collectors.toList())) { if (first) { @@ -539,7 +550,7 @@ private void addIOStateInterfacesToStateChannels(Set visited, EState s) { tmp += SuccessorInterfaceGenerator.getSuccessorInterfaceName(a); }*/ - EState succ = s.getSuccessor(a); + EState succ = s.getDetSuccessor(a); if (succ.isTerminal()) { tmp += ScribSockGen.GENERATED_ENDSOCKET_NAME; @@ -628,9 +639,9 @@ private void addIOStateInterfacesToStateChannels(Set visited, EState s) } visited.add(s); - for (EAction a : s.getActions()) + for (EAction a : s.getDetActions()) { - addIOStateInterfacesToStateChannels(visited, s.getSuccessor(a)); + addIOStateInterfacesToStateChannels(visited, s.getDetSuccessor(a)); } } @@ -673,7 +684,7 @@ private void addSupertypeInterfaces() } res.putAll(tmp);*/ } - res.values().forEach((r) -> subtypeifs.put(r.getName(), r)); + res.values().forEach(r -> subtypeifs.put(r.getName(), r)); } } } @@ -893,8 +904,8 @@ private static MethodBuilder addToCastMethod(InterfaceBuilder ib, String ret) } else { - ib.addImports("org.scribble.main.RuntimeScribbleException"); - mb.addBodyLine("throw new RuntimeScribbleException(\"Invalid cast to EndSocket: \" + cast);"); + ib.addImports("org.scribble.util.RuntimeScribException"); + mb.addBodyLine("throw new RuntimeScribException(\"Invalid cast to EndSocket: \" + cast);"); } return mb; } @@ -925,8 +936,8 @@ private static MethodBuilder addEndSocketToCastMethod(ClassBuilder cb, String re private String getConcreteSuccessorParameters(EState s) { return "<" + - s.getActions().stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR) - .map((a) -> this.getSuccName.apply(s.getSuccessor(a))).collect(Collectors.joining(", ")) + s.getDetActions().stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR) + .map((a) -> this.getSuccName.apply(s.getDetSuccessor(a))).collect(Collectors.joining(", ")) + ">"; } @@ -978,7 +989,7 @@ private void collectBranchSuccs() String key = HandleIfaceGen.getHandleInterfaceName(self, s); // HandleInterface name List curr1 = new LinkedList<>(); - this.branchPostActions.get(s).forEach((a) -> curr1.addAll(s.getSuccessor(a).getActions())); // TODO: flatmap + 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); @@ -1034,7 +1045,7 @@ protected Role getSelf() return this.apigen.getSelf(); } - protected static String getIOInterfacePackageName(GProtocolName gpn, Role self) + protected static String getIOInterfacePackageName(GProtoName gpn, Role self) { return SessionApiGenerator.getStateChannelPackageName(gpn, self) + ".ioifaces"; } diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/IOStateIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOStateIfaceGen.java similarity index 78% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/IOStateIfaceGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOStateIfaceGen.java index c51d98f09..5f48b4e65 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/IOStateIfaceGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOStateIfaceGen.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi.ioifaces; +package org.scribble.codegen.java.statechanapi.ioifaces; import java.util.Collections; import java.util.Comparator; @@ -20,18 +20,18 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; -import org.scribble.codegen.java.endpointapi.SessionApiGenerator; -import org.scribble.codegen.java.endpointapi.StateChannelApiGenerator; +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.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.Role; +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 @@ -58,13 +58,13 @@ public IOStateIfaceGen(StateChannelApiGenerator apigen, Map as = this.curr.getActions(); - List as = this.curr.getActions(); + List as = this.curr.getDetActions(); FieldBuilder cast = this.ib.newField("cast"); cast.addModifiers(TypeBuilder.PUBLIC, TypeBuilder.STATIC, TypeBuilder.FINAL); @@ -100,7 +100,7 @@ protected void addCastField() protected void addSuccessorParamsAndActionInterfaces() { int i = 1; - for (EAction a : this.curr.getActions().stream().sorted(IOACTION_COMPARATOR).collect(Collectors.toList())) + for (EAction a : this.curr.getDetActions().stream().sorted(IOACTION_COMPARATOR).collect(Collectors.toList())) { if (a.isSend() || a.isReceive()) // HACK FIXME { @@ -132,23 +132,23 @@ public static String getIOStateInterfaceName(Role self, EState s) switch (s.getStateKind()) { case OUTPUT: name = "Select"; break; - case UNARY_INPUT: name = "Receive"; break; - case POLY_INPUT: name = "Branch"; break; - case TERMINAL: throw new RuntimeScribbleException("Shouldn't get in here: " + s); + 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.getActions().stream().sorted(IOACTION_COMPARATOR) + 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 RuntimeScribbleException + public static void checkIOStateInterfaceNameLength(String name) throws RuntimeScribException { if (name.length() > 250) // .java { - throw new RuntimeScribbleException("I/O Interface name too long (max 255): " + name); + 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/endpointapi/ioifaces/SuccessorIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/SuccessorIfaceGen.java similarity index 86% rename from scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/SuccessorIfaceGen.java rename to scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/SuccessorIfaceGen.java index e67cf1807..fd448bfa3 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/java/endpointapi/ioifaces/SuccessorIfaceGen.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/SuccessorIfaceGen.java @@ -11,13 +11,13 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.codegen.java.endpointapi.ioifaces; +package org.scribble.codegen.java.statechanapi.ioifaces; -import org.scribble.codegen.java.endpointapi.StateChannelApiGenerator; +import org.scribble.codegen.java.statechanapi.StateChannelApiGenerator; import org.scribble.codegen.java.util.InterfaceBuilder; import org.scribble.codegen.java.util.JavaBuilder; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; public class SuccessorIfaceGen extends IOIfaceGen { 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 index 4d54e3754..19f5bc382 100644 --- 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 @@ -13,7 +13,7 @@ */ package org.scribble.codegen.java.util; -import org.scribble.main.RuntimeScribbleException; +import org.scribble.util.RuntimeScribException; public class ConstructorBuilder extends MethodBuilder { @@ -25,12 +25,12 @@ protected ConstructorBuilder(String name) @Override public void setName(String name) { - throw new RuntimeScribbleException("Invalid for constructor"); + throw new RuntimeScribException("Invalid for constructor"); } @Override public void setReturn(String ret) { - throw new RuntimeScribbleException("Invalid for constructor"); + 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 index f54315023..600237d1d 100644 --- 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 @@ -18,7 +18,7 @@ import java.util.List; import java.util.stream.Collectors; -import org.scribble.main.RuntimeScribbleException; +import org.scribble.util.RuntimeScribException; public class EnumBuilder extends TypeBuilder { @@ -72,48 +72,48 @@ protected String buildSignature(String enun) @Override public void setPackage(String packname) { - throw new RuntimeScribbleException("Invalid for enums"); + throw new RuntimeScribException("Invalid for enums"); } @Override public void addImports(String... imports) { - throw new RuntimeScribbleException("Invalid for enums"); + throw new RuntimeScribException("Invalid for enums"); } @Override public FieldBuilder newField(String name) { - throw new RuntimeScribbleException("Invalid for enums"); + throw new RuntimeScribException("Invalid for enums"); } @Override public AbstractMethodBuilder newAbstractMethod() { - throw new RuntimeScribbleException("Invalid for enums"); + throw new RuntimeScribException("Invalid for enums"); } @Override public ClassBuilder newTopLevelClass() { - throw new RuntimeScribbleException("Invalid for enums"); + throw new RuntimeScribException("Invalid for enums"); } @Override protected String buildFields(String clazz) { - throw new RuntimeScribbleException("Invalid for enums"); + throw new RuntimeScribException("Invalid for enums"); } @Override protected String buildMethods(String clazz) { - throw new RuntimeScribbleException("Invalid for enums"); + throw new RuntimeScribException("Invalid for enums"); } @Override protected String buildMemberTypes(String clazz) { - throw new RuntimeScribbleException("Invalid for enums"); + throw new RuntimeScribException("Invalid for enums"); } } 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 index 7dcaeff40..a8e9e02b9 100644 --- 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 @@ -26,6 +26,7 @@ public class MethodBuilder extends JavaBuilder 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() { @@ -68,6 +69,16 @@ 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) { @@ -110,6 +121,10 @@ protected String buildSignature(String meth) 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 + " "; 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 index 8e7c68200..a2029706a 100644 --- 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 @@ -167,6 +167,22 @@ public EnumBuilder newMemberEnum(String name) 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(); @@ -222,7 +238,7 @@ protected String buildFields(String clazz) if (!this.fields.isEmpty()) { clazz += "\n"; - clazz += this.fields.stream().map((fb) -> fb.build()).collect(Collectors.joining("\n")); + clazz += this.fields.stream().map(fb -> fb.build()).collect(Collectors.joining("\n")); } return clazz; } @@ -232,7 +248,7 @@ 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")); + clazz += this.methods.stream().map(mb -> mb.build()).collect(Collectors.joining("\n\n")); } return clazz; } @@ -242,7 +258,7 @@ protected String buildMemberTypes(String clazz) if (!this.memberTypes.isEmpty()) { clazz += "\n\n"; - clazz += this.memberTypes.stream().map((cb) -> cb.build()).collect(Collectors.joining("\n\n")); + clazz += this.memberTypes.stream().map(tb -> tb.build()).collect(Collectors.joining("\n\n")); } return clazz; } @@ -252,7 +268,7 @@ protected String buildTopLevelTypes(String clazz) if (!this.topLevelTypes.isEmpty()) { clazz += "\n\n"; - clazz += this.topLevelTypes.stream().map((cb) -> cb.build()).collect(Collectors.joining("\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 index 64d718c6e..15107eb99 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STActionBuilder.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STActionBuilder.java @@ -13,8 +13,8 @@ */ package org.scribble.codegen.statetype; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; public abstract class 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 index 87f662188..a60e2a424 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STBranchStateBuilder.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STBranchStateBuilder.java @@ -13,7 +13,7 @@ */ package org.scribble.codegen.statetype; -import org.scribble.model.endpoint.EState; +import org.scribble.core.model.endpoint.EState; public abstract class STBranchStateBuilder extends STStateChanBuilder { @@ -30,7 +30,7 @@ public String build(STStateChanAPIBuilder api, EState s) String out = getPreamble(api, s); out += "\n\n"; - out += this.bb.build(api, s, s.getActions().get(1)); // Getting 1 checks non-unary + 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/STCaseBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STCaseBuilder.java index bc3fc04bf..76de329b9 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STCaseBuilder.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STCaseBuilder.java @@ -13,9 +13,9 @@ */ package org.scribble.codegen.statetype; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.model.endpoint.actions.EReceive; +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 { @@ -31,10 +31,10 @@ public String build(STStateChanAPIBuilder api, EState s) { String out = getPreamble(api, s); - for (EAction a : s.getActions()) + for (EAction a : s.getDetActions()) { out += "\n\n"; - if (a instanceof EReceive) // FIXME: factor out action kind + if (a instanceof ERecv) // FIXME: factor out action kind { out += this.cb.build(api, s, a); } 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 index cc80d80b0..89abfb1c8 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STEndStateBuilder.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STEndStateBuilder.java @@ -13,7 +13,7 @@ */ package org.scribble.codegen.statetype; -import org.scribble.model.endpoint.EState; +import org.scribble.core.model.endpoint.EState; public abstract class STEndStateBuilder extends STStateChanBuilder { 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 index bd7ae7c8b..1f4a62ca2 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STOutputStateBuilder.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STOutputStateBuilder.java @@ -13,11 +13,11 @@ */ package org.scribble.codegen.statetype; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.model.endpoint.actions.ERequest; -import org.scribble.model.endpoint.actions.EDisconnect; -import org.scribble.model.endpoint.actions.ESend; +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 { @@ -36,14 +36,14 @@ public String build(STStateChanAPIBuilder api, EState s) + "\n" + "type " + getSTStateName(gpn, role, s) + " struct{}";*/ - for (EAction a : s.getActions()) + 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 ERequest) + else if (a instanceof EReq) { throw new RuntimeException("TODO: " + a); } 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 index dc5ebf640..d18309954 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STReceiveStateBuilder.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STReceiveStateBuilder.java @@ -15,8 +15,8 @@ import java.util.List; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; public abstract class STReceiveStateBuilder extends STStateChanBuilder { @@ -32,7 +32,7 @@ public String build(STStateChanAPIBuilder api, EState s) { String out = getPreamble(api, s); - List as = s.getActions(); + List as = s.getDetActions(); if (as.size() > 1) { throw new RuntimeException("Shouldn't get in here: " + as); 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 index a158f719a..493429f30 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STStateChanAPIBuilder.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STStateChanAPIBuilder.java @@ -18,19 +18,18 @@ import java.util.Map; import java.util.Set; -import org.scribble.main.Job; -import org.scribble.model.MState; -import org.scribble.model.endpoint.EGraph; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.Role; +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 GProtocolName gpn; + public final GProtoName gpn; public final Role role; public final EGraph graph; @@ -42,8 +41,9 @@ public abstract class STStateChanAPIBuilder private Map names = new HashMap<>(); - protected STStateChanAPIBuilder(Job job, GProtocolName gpn, Role role, EGraph graph, - STOutputStateBuilder ob, STReceiveStateBuilder rb, STBranchStateBuilder bb, STCaseBuilder cb, STEndStateBuilder eb) + protected STStateChanAPIBuilder(Job job, GProtoName gpn, Role role, + EGraph graph, STOutputStateBuilder ob, STReceiveStateBuilder rb, + STBranchStateBuilder bb, STCaseBuilder cb, STEndStateBuilder eb) { this.job = job; @@ -65,27 +65,27 @@ public Map build() // filepath -> source Map api = new HashMap<>(); Set states = new LinkedHashSet<>(); states.add(this.graph.init); - states.addAll(MState.getReachableStates(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_INPUT: + 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_INPUT: + 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 WRAP_SERVER: throw new RuntimeException("TODO"); + case SERVER_WRAP: throw new RuntimeException("TODO"); default: throw new RuntimeException("Shouldn't get in here: " + s); } } 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 index d2af364dc..aeca376a1 100644 --- a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STStateChanBuilder.java +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STStateChanBuilder.java @@ -13,7 +13,7 @@ */ package org.scribble.codegen.statetype; -import org.scribble.model.endpoint.EState; +import org.scribble.core.model.endpoint.EState; public abstract class STStateChanBuilder { diff --git a/scribble-core/pom.xml b/scribble-core/pom.xml index fd1965708..8ca744096 100644 --- a/scribble-core/pom.xml +++ b/scribble-core/pom.xml @@ -1,25 +1,26 @@ 4.0.0 + + scribble-core jar - scribble-core - - - org.scribble - parent - 0.4.4-SNAPSHOT - ../pom.xml - 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/ast/AstFactory.java b/scribble-core/src/main/java/org/scribble/ast/AstFactory.java deleted file mode 100644 index 44c2f2245..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/AstFactory.java +++ /dev/null @@ -1,154 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global.GChoice; -import org.scribble.ast.global.GConnect; -import org.scribble.ast.global.GContinue; -import org.scribble.ast.global.GDelegationElem; -import org.scribble.ast.global.GDisconnect; -import org.scribble.ast.global.GDo; -import org.scribble.ast.global.GInteractionNode; -import org.scribble.ast.global.GInteractionSeq; -import org.scribble.ast.global.GMessageTransfer; -import org.scribble.ast.global.GProtocolBlock; -import org.scribble.ast.global.GProtocolDecl; -import org.scribble.ast.global.GProtocolDef; -import org.scribble.ast.global.GProtocolHeader; -import org.scribble.ast.global.GRecursion; -import org.scribble.ast.global.GWrap; -import org.scribble.ast.local.LAccept; -import org.scribble.ast.local.LChoice; -import org.scribble.ast.local.LRequest; -import org.scribble.ast.local.LContinue; -import org.scribble.ast.local.LDelegationElem; -import org.scribble.ast.local.LDisconnect; -import org.scribble.ast.local.LDo; -import org.scribble.ast.local.LInteractionNode; -import org.scribble.ast.local.LInteractionSeq; -import org.scribble.ast.local.LProjectionDecl; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.ast.local.LProtocolDecl; -import org.scribble.ast.local.LProtocolDef; -import org.scribble.ast.local.LProtocolHeader; -import org.scribble.ast.local.LReceive; -import org.scribble.ast.local.LRecursion; -import org.scribble.ast.local.LSend; -import org.scribble.ast.local.LWrapClient; -import org.scribble.ast.local.LWrapServer; -import org.scribble.ast.local.SelfRoleDecl; -import org.scribble.ast.name.NameNode; -import org.scribble.ast.name.PayloadElemNameNode; -import org.scribble.ast.name.qualified.DataTypeNode; -import org.scribble.ast.name.qualified.GProtocolNameNode; -import org.scribble.ast.name.qualified.LProtocolNameNode; -import org.scribble.ast.name.qualified.MessageSigNameNode; -import org.scribble.ast.name.qualified.ModuleNameNode; -import org.scribble.ast.name.qualified.QualifiedNameNode; -import org.scribble.ast.name.simple.AmbigNameNode; -import org.scribble.ast.name.simple.DummyProjectionRoleNode; -import org.scribble.ast.name.simple.NonRoleParamNode; -import org.scribble.ast.name.simple.OpNode; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.type.kind.Kind; -import org.scribble.type.kind.NonRoleParamKind; -import org.scribble.type.kind.PayloadTypeKind; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.Role; - - -public interface AstFactory -{ - Module Module(CommonTree source, ModuleDecl moddecl, List> imports, List> data, List> protos); - - MessageSigNode MessageSigNode(CommonTree source, OpNode op, PayloadElemList payload); - - GDelegationElem GDelegationElem(CommonTree source, GProtocolNameNode name, RoleNode role); - LDelegationElem LDelegationElem(CommonTree source, LProtocolNameNode name); - - //PayloadElemList PayloadElemList(List> payloadelems); - PayloadElemList PayloadElemList(CommonTree source, List> payloadelems); - //PayloadElem PayloadElem(PayloadElemNameNode name); - //UnaryPayloadElem DataTypeElem(PayloadElemNameNode name); - //UnaryPayloadElem UnaryPayloadElem(PayloadElemNameNode name); - UnaryPayloadElem UnaryPayloadElem(CommonTree source, PayloadElemNameNode name); - - ModuleDecl ModuleDecl(CommonTree source, ModuleNameNode fullmodname); - ImportModule ImportModule(CommonTree source, ModuleNameNode modname, ModuleNameNode alias); - - MessageSigNameDecl MessageSigNameDecl(CommonTree source, String schema, String extName, String extSource, MessageSigNameNode name); - DataTypeDecl DataTypeDecl(CommonTree source, String schema, String extName, String extSource, DataTypeNode name); - - GProtocolDecl GProtocolDecl(CommonTree source, List modifiers, GProtocolHeader header, GProtocolDef def); - GProtocolHeader GProtocolHeader(CommonTree source, GProtocolNameNode name, RoleDeclList roledecls, NonRoleParamDeclList paramdecls); - - RoleDeclList RoleDeclList(CommonTree source, List rds); - RoleDecl RoleDecl(CommonTree source, RoleNode role); - //ConnectDecl ConnectDecl(CommonTree source, RoleNode src, RoleNode role); - NonRoleParamDeclList NonRoleParamDeclList(CommonTree source, List> pds); - NonRoleParamDecl NonRoleParamDecl(CommonTree source, K kind, NonRoleParamNode name); - - GProtocolDef GProtocolDef(CommonTree source, GProtocolBlock block); - GProtocolBlock GProtocolBlock(CommonTree source, GInteractionSeq gis); - GInteractionSeq GInteractionSeq(CommonTree source, List gis); - - GMessageTransfer GMessageTransfer(CommonTree source, RoleNode src, MessageNode msg, List dests); - GConnect GConnect(CommonTree source, RoleNode src, MessageNode msg, RoleNode dest); - //GConnect GConnect(CommonTree source, RoleNode src, RoleNode dest); - GDisconnect GDisconnect(CommonTree source, RoleNode src, RoleNode dest); - GWrap GWrap(CommonTree source, RoleNode src, RoleNode dest); - GChoice GChoice(CommonTree source, RoleNode subj, List blocks); - GRecursion GRecursion(CommonTree source, RecVarNode recvar, GProtocolBlock block); - GContinue GContinue(CommonTree source, RecVarNode recvar); - GDo GDo(CommonTree source, RoleArgList roles, NonRoleArgList args, GProtocolNameNode proto); - - RoleArgList RoleArgList(CommonTree source, List roles); - RoleArg RoleArg(CommonTree source, RoleNode role); - NonRoleArgList NonRoleArgList(CommonTree source, List args); - NonRoleArg NonRoleArg(CommonTree source, NonRoleArgNode arg); - - NameNode SimpleNameNode(CommonTree source, K kind, String identifier); - QualifiedNameNode QualifiedNameNode(CommonTree source, K kind, String... elems); - - AmbigNameNode AmbiguousNameNode(CommonTree source, String identifier); - NonRoleParamNode NonRoleParamNode(CommonTree source, K kind, String identifier); - DummyProjectionRoleNode DummyProjectionRoleNode(); - - 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); - LReceive LReceive(CommonTree source, RoleNode src, MessageNode msg, List dests); - LRequest LConnect(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-core/src/main/java/org/scribble/ast/AstFactoryImpl.java b/scribble-core/src/main/java/org/scribble/ast/AstFactoryImpl.java deleted file mode 100644 index b175f23ce..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/AstFactoryImpl.java +++ /dev/null @@ -1,695 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.global.GChoice; -import org.scribble.ast.global.GConnect; -import org.scribble.ast.global.GContinue; -import org.scribble.ast.global.GDelegationElem; -import org.scribble.ast.global.GDisconnect; -import org.scribble.ast.global.GDo; -import org.scribble.ast.global.GInteractionNode; -import org.scribble.ast.global.GInteractionSeq; -import org.scribble.ast.global.GMessageTransfer; -import org.scribble.ast.global.GProtocolBlock; -import org.scribble.ast.global.GProtocolDecl; -import org.scribble.ast.global.GProtocolDef; -import org.scribble.ast.global.GProtocolHeader; -import org.scribble.ast.global.GRecursion; -import org.scribble.ast.global.GWrap; -import org.scribble.ast.local.LAccept; -import org.scribble.ast.local.LChoice; -import org.scribble.ast.local.LRequest; -import org.scribble.ast.local.LContinue; -import org.scribble.ast.local.LDelegationElem; -import org.scribble.ast.local.LDisconnect; -import org.scribble.ast.local.LDo; -import org.scribble.ast.local.LInteractionNode; -import org.scribble.ast.local.LInteractionSeq; -import org.scribble.ast.local.LProjectionDecl; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.ast.local.LProtocolDecl; -import org.scribble.ast.local.LProtocolDef; -import org.scribble.ast.local.LProtocolHeader; -import org.scribble.ast.local.LReceive; -import org.scribble.ast.local.LRecursion; -import org.scribble.ast.local.LSend; -import org.scribble.ast.local.LWrapClient; -import org.scribble.ast.local.LWrapServer; -import org.scribble.ast.local.SelfRoleDecl; -import org.scribble.ast.name.NameNode; -import org.scribble.ast.name.PayloadElemNameNode; -import org.scribble.ast.name.qualified.DataTypeNode; -import org.scribble.ast.name.qualified.GProtocolNameNode; -import org.scribble.ast.name.qualified.LProtocolNameNode; -import org.scribble.ast.name.qualified.MessageSigNameNode; -import org.scribble.ast.name.qualified.ModuleNameNode; -import org.scribble.ast.name.qualified.QualifiedNameNode; -import org.scribble.ast.name.simple.AmbigNameNode; -import org.scribble.ast.name.simple.DummyProjectionRoleNode; -import org.scribble.ast.name.simple.NonRoleParamNode; -import org.scribble.ast.name.simple.OpNode; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.DefaultDel; -import org.scribble.del.ImportModuleDel; -import org.scribble.del.ModuleDel; -import org.scribble.del.NonRoleArgListDel; -import org.scribble.del.NonRoleParamDeclDel; -import org.scribble.del.NonRoleParamDeclListDel; -import org.scribble.del.RoleArgListDel; -import org.scribble.del.RoleDeclDel; -import org.scribble.del.RoleDeclListDel; -import org.scribble.del.ScribDel; -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.GProtocolBlockDel; -import org.scribble.del.global.GProtocolDeclDel; -import org.scribble.del.global.GProtocolDefDel; -import org.scribble.del.global.GRecursionDel; -import org.scribble.del.global.GWrapDel; -import org.scribble.del.local.LAcceptDel; -import org.scribble.del.local.LChoiceDel; -import org.scribble.del.local.LRequestDel; -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.LProtocolBlockDel; -import org.scribble.del.local.LProtocolDeclDel; -import org.scribble.del.local.LProtocolDefDel; -import org.scribble.del.local.LReceiveDel; -import org.scribble.del.local.LRecursionDel; -import org.scribble.del.local.LSendDel; -import org.scribble.del.local.LWrapClientDel; -import org.scribble.del.local.LWrapServerDel; -import org.scribble.del.name.AmbigNameNodeDel; -import org.scribble.del.name.DataTypeNodeDel; -import org.scribble.del.name.MessageSigNameNodeDel; -import org.scribble.del.name.ParamNodeDel; -import org.scribble.del.name.RecVarNodeDel; -import org.scribble.del.name.RoleNodeDel; -import org.scribble.type.kind.DataTypeKind; -import org.scribble.type.kind.Global; -import org.scribble.type.kind.Kind; -import org.scribble.type.kind.Local; -import org.scribble.type.kind.ModuleKind; -import org.scribble.type.kind.NonRoleParamKind; -import org.scribble.type.kind.OpKind; -import org.scribble.type.kind.PayloadTypeKind; -import org.scribble.type.kind.RecVarKind; -import org.scribble.type.kind.RoleKind; -import org.scribble.type.kind.SigKind; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.Op; -import org.scribble.type.name.Role; - - -public class AstFactoryImpl implements AstFactory -{ - //public static final AstFactory FACTORY = new AstFactoryImpl(); - - private static MessageSigNode UNIT_MESSAGE_SIG_NODE; // A "constant" - - public AstFactoryImpl() - { - - } - - // FIXME: inconsistent wrt. this.source -- it is essentially parsed (in the sense of *omitted* syntax), but not recorded - // FIXME: this pattern is not ideal ("exposed" public constructor arg in GWrap/GDisconnect) - // An alternative would be to make subclasses, e.g., UnitMessageSigNode, UnitOp, EmptyPayloadElemList -- but a lot of extra classes - protected MessageSigNode UnitMessageSigNode() - { - if (UNIT_MESSAGE_SIG_NODE == null) - { - UNIT_MESSAGE_SIG_NODE = MessageSigNode(null, (OpNode) SimpleNameNode(null, OpKind.KIND, Op.EMPTY_OPERATOR.toString()), - PayloadElemList(null, Collections.emptyList())); // Payload.EMPTY_PAYLOAD? - } - return UNIT_MESSAGE_SIG_NODE; - } - - @Override - public MessageSigNode MessageSigNode(CommonTree source, OpNode op, PayloadElemList payload) - { - MessageSigNode msn = new MessageSigNode(source, op, payload); - msn = del(msn, createDefaultDelegate()); - return msn; - } - - @Override - //public PayloadElemList PayloadElemList(List payloadelems) - public PayloadElemList PayloadElemList(CommonTree source, List> payloadelems) - { - PayloadElemList p = new PayloadElemList(source, payloadelems); - p = del(p, createDefaultDelegate()); - return p; - } - - /*@Override - public PayloadElem PayloadElem(PayloadElemNameNode name) - { - PayloadElem pe = new PayloadElem(name); - pe = del(pe, createDefaultDelegate()); - return pe; - }*/ - - @Override - //public UnaryPayloadElem DataTypeElem(PayloadElemNameNode name) - //public UnaryPayloadElem UnaryPayloadElem(PayloadElemNameNode name) - public UnaryPayloadElem UnaryPayloadElem(CommonTree source, PayloadElemNameNode name) - { - UnaryPayloadElem de= new UnaryPayloadElem<>(source, name); - de = del(de, createDefaultDelegate()); - return de; - } - - @Override - public GDelegationElem GDelegationElem(CommonTree source, GProtocolNameNode proto, RoleNode role) - { - GDelegationElem de = new GDelegationElem(source, proto, role); - //de = del(de, createDefaultDelegate()); - de = del(de, new GDelegationElemDel()); // FIXME: GDelegationElemDel - return de; - } - - @Override - public LDelegationElem LDelegationElem(CommonTree source, LProtocolNameNode proto) - { - LDelegationElem de = new LDelegationElem(source, proto); - de = del(de, createDefaultDelegate()); - return de; - } - - @Override - public Module Module(CommonTree source, ModuleDecl moddecl, List> imports, List> data, List> protos) - { - Module module = new Module(source, moddecl, imports, data, protos); - module = del(module, new ModuleDel()); - return module; - } - - @Override - public ModuleDecl ModuleDecl(CommonTree source, ModuleNameNode fullmodname) - { - ModuleDecl md = new ModuleDecl(source, fullmodname); - md = del(md, createDefaultDelegate()); - return md; - } - - @Override - public ImportModule ImportModule(CommonTree source, ModuleNameNode modname, ModuleNameNode alias) - { - ImportModule im = new ImportModule(source, modname, alias); - im = del(im, new ImportModuleDel()); - return im; - } - - @Override - public MessageSigNameDecl MessageSigNameDecl(CommonTree source, String schema, String extName, String extSource, MessageSigNameNode alias) - { - MessageSigNameDecl msd = new MessageSigNameDecl(source, schema, extName, extSource, alias); - msd = del(msd, createDefaultDelegate()); - return msd; - } - - @Override - public DataTypeDecl DataTypeDecl(CommonTree source, String schema, String extName, String extSource, DataTypeNode alias) - { - DataTypeDecl dtd = new DataTypeDecl(source, schema, extName, extSource, alias); - dtd = del(dtd, createDefaultDelegate()); - return dtd; - } - - @Override - public GProtocolDecl GProtocolDecl(CommonTree source, List mods, GProtocolHeader header, GProtocolDef def) - { - GProtocolDecl gpd = new GProtocolDecl(source, mods, header, def); - gpd = del(gpd, new GProtocolDeclDel()); - return gpd; - } - - @Override - public GProtocolHeader GProtocolHeader(CommonTree source, GProtocolNameNode name, RoleDeclList roledecls, NonRoleParamDeclList paramdecls) - { - GProtocolHeader gph = new GProtocolHeader(source, name, roledecls, paramdecls); - gph = del(gph, createDefaultDelegate()); - return gph; - } - - @Override - public RoleDeclList RoleDeclList(CommonTree source, List rds) - { - RoleDeclList rdl = new RoleDeclList(source, rds); - rdl = del(rdl, new RoleDeclListDel()); - return rdl; - } - - @Override - public RoleDecl RoleDecl(CommonTree source, RoleNode namenode) - { - RoleDecl rd = new RoleDecl(source, namenode); - rd = del(rd, new RoleDeclDel()); - return rd; - } - - /*@Override - public ConnectDecl ConnectDecl(RoleNode src, RoleNode role) - { - ConnectDecl cd = new ConnectDecl(src, role); - cd = del(cd, new ConnectDeclDel()); - return cd; - }*/ - - @Override - public NonRoleParamDeclList NonRoleParamDeclList(CommonTree source, List> pds) - { - NonRoleParamDeclList pdl = new NonRoleParamDeclList(source, pds); - pdl = del(pdl, new NonRoleParamDeclListDel()); - return pdl; - } - - @Override - public NonRoleParamDecl NonRoleParamDecl(CommonTree source, K kind, NonRoleParamNode namenode) - { - NonRoleParamDecl pd = new NonRoleParamDecl(source, kind, namenode); - pd = del(pd, new NonRoleParamDeclDel()); - return pd; - } - - @Override - public GProtocolDef GProtocolDef(CommonTree source, GProtocolBlock block) - { - GProtocolDef gpd = new GProtocolDef(source, block); - gpd = del(gpd, new GProtocolDefDel()); - return gpd; - } - - @Override - public GProtocolBlock GProtocolBlock(CommonTree source, GInteractionSeq seq) - { - GProtocolBlock gpb = new GProtocolBlock(source, seq); - gpb = del(gpb, new GProtocolBlockDel()); - return gpb; - } - - @Override - public GInteractionSeq GInteractionSeq(CommonTree source, List actions) - { - GInteractionSeq gis = new GInteractionSeq(source, actions); - gis = del(gis, new GInteractionSeqDel()); - return gis; - } - - @Override - public GMessageTransfer GMessageTransfer(CommonTree source, RoleNode src, MessageNode msg, List dests) - { - GMessageTransfer gmt = new GMessageTransfer(source, src, msg, dests); - gmt = del(gmt, new GMessageTransferDel()); - return gmt; - } - - @Override - public GConnect GConnect(CommonTree source, RoleNode src, MessageNode msg, RoleNode dest) - //public GConnect GConnect(RoleNode src, RoleNode dest) - { - GConnect gc = new GConnect(source, src, msg, dest); - //GConnect gc = new GConnect(src, dest); - gc = del(gc, new GConnectDel()); - return gc; - } - - @Override - public GDisconnect GDisconnect(CommonTree source, RoleNode src, RoleNode dest) - { - GDisconnect gc = new GDisconnect(source, UnitMessageSigNode(), src, dest); - gc = del(gc, new GDisconnectDel()); - return gc; - } - - @Override - public GWrap GWrap(CommonTree source, RoleNode src, RoleNode dest) - { - GWrap gw = new GWrap(source, UnitMessageSigNode(), src, dest); - gw = del(gw, new GWrapDel()); - return gw; - } - - @Override - public GChoice GChoice(CommonTree source, RoleNode subj, List blocks) - { - GChoice gc = new GChoice(source, subj, blocks); - gc = del(gc, new GChoiceDel()); - return gc; - } - - @Override - public GRecursion GRecursion(CommonTree source, RecVarNode recvar, GProtocolBlock block) - { - GRecursion gr = new GRecursion(source, recvar, block); - gr = del(gr, new GRecursionDel()); - return gr; - } - - @Override - public GContinue GContinue(CommonTree source, RecVarNode recvar) - { - GContinue gc = new GContinue(source, recvar); - gc = del(gc, new GContinueDel()); - return gc; - } - - @Override - public GDo GDo(CommonTree source, RoleArgList roleinstans, NonRoleArgList arginstans, GProtocolNameNode proto) - { - GDo gd = new GDo(source, roleinstans, arginstans, proto); - gd = del(gd, new GDoDel()); - return gd; - } - - @Override - public RoleArgList RoleArgList(CommonTree source, List ris) - { - RoleArgList rdl = new RoleArgList(source, ris); - rdl = del(rdl, new RoleArgListDel()); - return rdl; - } - - @Override - public RoleArg RoleArg(CommonTree source, RoleNode role) - { - RoleArg ri = new RoleArg(source, role); - ri = del(ri, createDefaultDelegate()); - return ri; - } - - @Override - public NonRoleArgList NonRoleArgList(CommonTree source, List ais) - { - NonRoleArgList rdl = new NonRoleArgList(source, ais); - rdl = del(rdl, new NonRoleArgListDel()); - return rdl; - } - - @Override - public NonRoleArg NonRoleArg(CommonTree source, NonRoleArgNode arg) - { - NonRoleArg ri = new NonRoleArg(source, arg); - ri = del(ri, createDefaultDelegate()); - return ri; - } - - @Override - public NameNode SimpleNameNode(CommonTree source, K kind, String identifier) - { - NameNode snn = null; - - // "Custom" del's - if (kind.equals(RecVarKind.KIND)) - { - snn = new RecVarNode(source, identifier); - snn = del(snn, new RecVarNodeDel()); - } - else if (kind.equals(RoleKind.KIND)) - { - snn = new RoleNode(source, identifier); - snn = del(snn, new RoleNodeDel()); - } - if (snn != null) - { - return castNameNode(kind, snn); - } - - // Default del's - if (kind.equals(OpKind.KIND)) - { - snn = new OpNode(source, identifier); - } - else - { - throw new RuntimeException("Shouldn't get in here: " + kind); - } - return castNameNode(kind, del(snn, createDefaultDelegate())); - } - - @Override - public QualifiedNameNode QualifiedNameNode(CommonTree source, K kind, String... elems) - { - QualifiedNameNode qnn = null; - if (kind.equals(SigKind.KIND)) - { - qnn = new MessageSigNameNode(source, elems); - qnn = del(qnn, new MessageSigNameNodeDel()); - } - else if (kind.equals(DataTypeKind.KIND)) - { - qnn = new DataTypeNode(source, elems); - qnn = del(qnn, new DataTypeNodeDel()); - } - if (qnn != null) - { - return castNameNode(kind, qnn); - } - - if (kind.equals(ModuleKind.KIND)) - { - qnn = new ModuleNameNode(source, elems); - } - else if (kind.equals(Global.KIND)) - { - qnn = new GProtocolNameNode(source, elems); - } - else if (kind.equals(Local.KIND)) - { - qnn = new LProtocolNameNode(source,elems); - } - else - { - throw new RuntimeException("Shouldn't get in here: " + kind); - } - return castNameNode(kind, del(qnn, createDefaultDelegate())); - } - - protected static , K extends Kind> T castNameNode(K kind, NameNode n) - { - if (!n.toName().getKind().equals(kind)) - { - throw new RuntimeException("Shouldn't get in here: " + kind + ", " + n); - } - @SuppressWarnings("unchecked") - T tmp = (T) n; - return tmp; - } - - @Override - public AmbigNameNode AmbiguousNameNode(CommonTree source, String identifier) - { - AmbigNameNode ann = new AmbigNameNode(source, identifier); - ann = (AmbigNameNode) ann.del(new AmbigNameNodeDel()); - return ann; - } - - @Override - public NonRoleParamNode NonRoleParamNode(CommonTree source, K kind, String identifier) - { - NonRoleParamNode pn = new NonRoleParamNode(source, kind, identifier); - pn = del(pn, new ParamNodeDel()); - return pn; - } - - @Override - public DummyProjectionRoleNode DummyProjectionRoleNode() - { - DummyProjectionRoleNode dprn = new DummyProjectionRoleNode(); - dprn = (DummyProjectionRoleNode) dprn.del(createDefaultDelegate()); - return dprn; - } - - @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 = ScribNodeBase.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 LReceive LReceive(CommonTree source, RoleNode src, MessageNode msg, List dests) - { - LReceive ls = new LReceive(source, src, msg, dests); - ls = del(ls, new LReceiveDel()); - return ls; - } - - @Override - public LRequest LConnect(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; - } - - protected ScribDel createDefaultDelegate() - { - return new DefaultDel(); - } - - // FIXME: factor out - //@SuppressWarnings("unchecked") - protected static T del(T n, ScribDel del) - { - /*ScribNodeBase ret = n.del(del); // FIXME: del makes another shallow copy of n - if (ret.getClass() != n.getClass()) - { - throw new RuntimeException("Shouldn't get in here: " + ret.getClass() + ", " + n.getClass()); - } - return (T) ret;*/ - return ScribNodeBase.del(n, del); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/Choice.java b/scribble-core/src/main/java/org/scribble/ast/Choice.java deleted file mode 100644 index 5559358a3..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/Choice.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.LinkedList; -import java.util.List; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.visit.AstVisitor; - -public abstract class Choice extends CompoundInteractionNode -{ - public final RoleNode subj; - private final List> blocks; - // Factor up? And specialise to singleton for Recursion/Interruptible? Maybe too artificial -- could separate unaryblocked and multiblocked compound ops? - - protected Choice(CommonTree source, RoleNode subj, List> blocks) - { - super(source); - this.subj = subj; - this.blocks = new LinkedList<>(blocks); - } - - public abstract Choice reconstruct(RoleNode subj, List> blocks); - - @Override - public Choice visitChildren(AstVisitor nv) throws ScribbleException - { - RoleNode subj = (RoleNode) visitChild(this.subj, nv); - List> blocks = visitChildListWithClassEqualityCheck(this, this.blocks, nv); - return reconstruct(subj, blocks); - } - - public List> getBlocks() - { - return Collections.unmodifiableList(this.blocks); - } - - @Override - public String toString() - { - String sep = " " + Constants.OR_KW + " "; - return Constants.CHOICE_KW + " " + Constants.AT_KW + " " + this.subj + " " - + this.blocks.stream().map((b) -> b.toString()).collect(Collectors.joining(sep)); - } - - /*@Override - public Map getEnablingMessages() - { - - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/CompoundInteraction.java b/scribble-core/src/main/java/org/scribble/ast/CompoundInteraction.java deleted file mode 100644 index 6d359df19..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/CompoundInteraction.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; - -// ProtocolBlock or CompoundInteractionNode -public abstract class CompoundInteraction extends ScribNodeBase -{ - public CompoundInteraction(CommonTree source) - { - super(source); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/CompoundInteractionNode.java b/scribble-core/src/main/java/org/scribble/ast/CompoundInteractionNode.java deleted file mode 100644 index eafdb5574..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/CompoundInteractionNode.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.type.kind.ProtocolKind; - -// Name should be read (Compound ( InteractionNode )) -public abstract class CompoundInteractionNode - extends CompoundInteraction implements InteractionNode -{ - protected CompoundInteractionNode(CommonTree source) - { - super(source); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/ConnectionAction.java b/scribble-core/src/main/java/org/scribble/ast/ConnectionAction.java deleted file mode 100644 index bbdb11151..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/ConnectionAction.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.visit.AstVisitor; - -// FIXME: factor with MessageTransfer -public abstract class ConnectionAction extends SimpleInteractionNode -{ - public final RoleNode src; - public final MessageNode msg; - public final RoleNode dest; - - protected ConnectionAction(CommonTree source, RoleNode src, MessageNode msg, RoleNode dest) - //protected ConnectionAction(RoleNode src, RoleNode dest) - { - super(source); - this.src = src; - this.msg = msg; - this.dest = dest; - } - - public abstract ConnectionAction reconstruct(RoleNode src, MessageNode msg, RoleNode dest); - //public abstract ConnectionAction reconstruct(RoleNode src, RoleNode dest); - - @Override - public ConnectionAction visitChildren(AstVisitor nv) throws ScribbleException - { - RoleNode src = (RoleNode) visitChild(this.src, nv); - MessageNode msg = (MessageNode) visitChild(this.msg, nv); - RoleNode dest = (RoleNode) visitChild(this.dest, nv); - return reconstruct(src, msg, dest); - //return reconstruct(src, dest); - } - - @Override - public abstract String toString(); - - protected boolean isUnitMessage() - { - if (!this.msg.isMessageSigNode()) - { - return false; - } - MessageSigNode msn = (MessageSigNode) this.msg; - return msn.op.isEmpty() && msn.payloads.isEmpty(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/Constants.java b/scribble-core/src/main/java/org/scribble/ast/Constants.java deleted file mode 100644 index fb62cde91..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/Constants.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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; - - -// FIXME: cannot use AntlrConstants from org.scribble.parser 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 TYPE_KW = "type"; - 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"; -} diff --git a/scribble-core/src/main/java/org/scribble/ast/Continue.java b/scribble-core/src/main/java/org/scribble/ast/Continue.java deleted file mode 100644 index 1df574667..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/Continue.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.visit.AstVisitor; - -public abstract class Continue extends SimpleInteractionNode -{ - public final RecVarNode recvar; - - protected Continue(CommonTree source, RecVarNode recvar) - { - super(source); - this.recvar = recvar; - } - - public abstract Continue reconstruct(RecVarNode recvar); - - @Override - public Continue visitChildren(AstVisitor nv) throws ScribbleException - { - RecVarNode recvar = (RecVarNode) visitChild(this.recvar, nv); - return reconstruct(recvar); - } - - @Override - public String toString() - { - return Constants.CONTINUE_KW + " " + this.recvar + ";"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/DataTypeDecl.java b/scribble-core/src/main/java/org/scribble/ast/DataTypeDecl.java deleted file mode 100644 index b0ee07221..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/DataTypeDecl.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.qualified.DataTypeNode; -import org.scribble.ast.name.qualified.MemberNameNode; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.DataTypeKind; -import org.scribble.type.name.DataType; -import org.scribble.type.name.ModuleName; - -public class DataTypeDecl extends NonProtocolDecl -{ - public DataTypeDecl(CommonTree source, String schema, String extName, String extSource, DataTypeNode name) - { - super(source, schema, extName, extSource, name); - } - - @Override - protected ScribNodeBase copy() - { - return new DataTypeDecl(this.source, this.schema, this.extName, this.extSource, getNameNode()); - } - - @Override - public DataTypeDecl clone(AstFactory af) - { - DataTypeNode name = (DataTypeNode) this.name.clone(af); - return af.DataTypeDecl(this.source, this.schema, this.extName, this.extSource, name); - } - - @Override - public DataTypeDecl reconstruct(String schema, String extName, String extSource, MemberNameNode name) - { - ScribDel del = del(); - DataTypeDecl dtd = new DataTypeDecl(this.source, schema, extName, extSource, (DataTypeNode) name); - dtd = (DataTypeDecl) dtd.del(del); - return dtd; - } - - @Override - public boolean isDataTypeDecl() - { - return true; - } - - @Override - public DataTypeNode getNameNode() - { - return (DataTypeNode) super.getNameNode(); - } - - @Override - public DataType getDeclName() - { - return (DataType) super.getDeclName(); - } - - @Override - public DataType getFullMemberName(Module mod) - { - ModuleName fullmodname = mod.getFullModuleName(); - return new DataType(fullmodname, getDeclName()); - } - - @Override - public String toString() - { - return Constants.TYPE_KW + " <" + this.schema + "> " + this.extName - + " " + Constants.FROM_KW + " " + this.extSource + " " - + Constants.AS_KW + " " + this.name + ";"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/Do.java b/scribble-core/src/main/java/org/scribble/ast/Do.java deleted file mode 100644 index a9472b39c..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/Do.java +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.context.ModuleContext; -import org.scribble.ast.name.qualified.ProtocolNameNode; -import org.scribble.main.JobContext; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.ProtocolName; -import org.scribble.type.name.Role; -import org.scribble.visit.AstVisitor; - -public abstract class Do extends SimpleInteractionNode //implements ScopedNode -{ - //public final ScopeNode scope; - public final RoleArgList roles; - public final NonRoleArgList args; - public final ProtocolNameNode proto; // Maybe use an "Ambiguous" version until names resolved -- is a visible protocol, but not necessarily a simple or full member name - - protected Do(CommonTree source, RoleArgList roleinstans, NonRoleArgList arginstans, ProtocolNameNode proto) - { - super(source); - //this.scope = scope; - this.roles = roleinstans; - this.args = arginstans; - this.proto = proto; - } - - public abstract Do reconstruct(RoleArgList roleinstans, NonRoleArgList arginstans, ProtocolNameNode proto); - - public abstract ProtocolNameNode getProtocolNameNode(); - - @Override - public Do visitChildren(AstVisitor nv) throws ScribbleException - { - //ScopeNode scope = isScoped() ? (ScopeNode) visitChild(this.scope, nv) : null; - RoleArgList ril = (RoleArgList) visitChild(this.roles, nv); - NonRoleArgList al = (NonRoleArgList) visitChild(this.args, nv); - ProtocolNameNode proto = visitChildWithClassEqualityCheck(this, this.proto, nv); - return reconstruct(ril, al, proto); - } - - // FIXME: mcontext now redundant because NameDisambiguator converts all targets to full names - // 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 ProtocolName getTargetProtocolDeclFullName(ModuleContext mcontext) - { - //return mcontext.checkProtocolDeclDependencyFullName(this.proto.toName()); - return this.proto.toName(); // Pre: use after name disambiguation (maybe drop FullName suffix) - } - - // mcontext redundant because redundant for getTargetProtocolDeclFullName - public ProtocolDecl getTargetProtocolDecl(JobContext jcontext, ModuleContext mcontext) - { - ProtocolName fullname = getTargetProtocolDeclFullName(mcontext); - return jcontext.getModule(fullname.getPrefix()).getProtocolDecl(fullname.getSimpleName()); - } - - public Role getTargetRoleParameter(JobContext jcontext, ModuleContext mcontext, Role role) - { - Iterator args = this.roles.getRoles().iterator(); - Iterator params = getTargetProtocolDecl(jcontext, mcontext).header.roledecls.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 boolean isEmptyScope() - { - return this.scope == null; - } - - @Override - //public Scope getScope() - public SimpleName getScopeElement() - { - return this.scope.toName(); - } - - public boolean isScoped() - { - return this.scope != null; - }*/ - - @Override - public String toString() - { - String s = Constants.DO_KW + " "; - //if (!hasEmptyScopeNode()) - /*if (isScoped()) - { - s += this.scope + ":"; - }*/ - return s + this.proto + this.args + this.roles + ";"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/DoArg.java b/scribble-core/src/main/java/org/scribble/ast/DoArg.java deleted file mode 100644 index 6a7039d8c..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/DoArg.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.Role; -import org.scribble.visit.AstVisitor; - -// 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 -{ - public final T val; - - protected DoArg(CommonTree source, T arg) - { - super(source); - this.val = arg; - } - - public abstract DoArg reconstruct(T arg); - - @Override - public DoArg visitChildren(AstVisitor nv) throws ScribbleException - { - ScribNode visited = visitChild(this.val, nv); // Disambiguation will replace AmbiguousNameNodes*/ - if (!(visited instanceof DoArgNode)) - { - throw new RuntimeException("Shouldn't get in here: " + visited); - } - @SuppressWarnings("unchecked") - T arg = (T) visited; - return reconstruct(arg); - } - - public T getVal() - { - return this.val; - } - - public abstract DoArg project(AstFactory af, Role self); - - @Override - public String toString() - { - return this.val.toString(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/DoArgList.java b/scribble-core/src/main/java/org/scribble/ast/DoArgList.java deleted file mode 100644 index 031cd326d..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/DoArgList.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.LinkedList; -import java.util.List; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.Role; -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 -{ - private final List args; - - public DoArgList(CommonTree source, List is) - { - super(source); - this.args = new LinkedList<>(is); - } - - public abstract DoArgList reconstruct(List instans); - - public abstract DoArgList project(AstFactory af, Role self); - - @Override - public DoArgList visitChildren(AstVisitor nv) throws ScribbleException - { - List nds = visitChildListWithClassEqualityCheck(this, this.args, nv); - return reconstruct(nds); - } - - public List getDoArgs() - { - return Collections.unmodifiableList(this.args); - } - - public int length() - { - return this.args.size(); - } - - // Like HeaderParamDeclList, without enclosing braces -- added by subclasses - @Override - public String toString() - { - return this.args.stream().map((a) -> a.toString()).collect(Collectors.joining(", ")); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/HeaderParamDecl.java b/scribble-core/src/main/java/org/scribble/ast/HeaderParamDecl.java deleted file mode 100644 index 4b248714e..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/HeaderParamDecl.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.simple.SimpleNameNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ParamKind; -import org.scribble.type.name.Role; -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 HeaderParamDecl extends NameDeclNode -{ - protected HeaderParamDecl(CommonTree source, SimpleNameNode name) - { - super(source, name); - } - - public abstract HeaderParamDecl reconstruct(SimpleNameNode name); - - @Override - public HeaderParamDecl visitChildren(AstVisitor nv) throws ScribbleException - { - SimpleNameNode name = visitChildWithClassEqualityCheck(this, (SimpleNameNode) this.name, nv); - return reconstruct(name); - } - - public abstract HeaderParamDecl project(AstFactory af, Role self); // Move to delegate? - - public abstract String getKeyword(); - - @Override - public String toString() - { - return getKeyword() + " " + getDeclName().toString(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/HeaderParamDeclList.java b/scribble-core/src/main/java/org/scribble/ast/HeaderParamDeclList.java deleted file mode 100644 index 2e4a538fd..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/HeaderParamDeclList.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.LinkedList; -import java.util.List; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ParamKind; -import org.scribble.type.name.Role; -import org.scribble.visit.AstVisitor; - - -// RoleKind or (NonRole)ParamKind -public abstract class HeaderParamDeclList extends ScribNodeBase -{ - private final List> decls; - - protected HeaderParamDeclList(CommonTree source, List> decls) - { - super(source); - this.decls = new LinkedList<>(decls); - } - - public abstract HeaderParamDeclList reconstruct(List> decls); - - @Override - public HeaderParamDeclList visitChildren(AstVisitor nv) throws ScribbleException - { - List> nds = visitChildListWithClassEqualityCheck(this, this.decls, nv); - return reconstruct(nds); - } - - public List> getDecls() - { - return Collections.unmodifiableList(this.decls); - } - - public abstract HeaderParamDeclList project(AstFactory af, Role self); // FIXME: move to delegate - - public int length() - { - return this.decls.size(); - } - - public boolean isEmpty() - { - return this.decls.isEmpty(); - } - - // Without enclosing braces -- added by subclasses - @Override - public String toString() - { - return this.decls.stream().map((nd) -> nd.toString()).collect(Collectors.joining(", ")); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/ImportDecl.java b/scribble-core/src/main/java/org/scribble/ast/ImportDecl.java deleted file mode 100644 index 3360596cc..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/ImportDecl.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.type.kind.ImportKind; -import org.scribble.type.name.Name; - -// TODO: factor out stuff from ImportModule and ImportMember into here, e.g. alias/name, reconstruct -public abstract class ImportDecl extends ScribNodeBase//, ModuleMember //implements NameDeclaration -{ - protected ImportDecl(CommonTree source) - { - super(source); - } - - public abstract boolean isAliased(); - public abstract Name getAlias(); - //public abstract Name getVisibleName(); - - public boolean isImportModule() - { - return false; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/ImportModule.java b/scribble-core/src/main/java/org/scribble/ast/ImportModule.java deleted file mode 100644 index d2a46a235..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/ImportModule.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.qualified.ModuleNameNode; -import org.scribble.del.ScribDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ModuleKind; -import org.scribble.type.name.ModuleName; -import org.scribble.visit.AstVisitor; - -public class ImportModule extends ImportDecl -{ - public final ModuleNameNode modname; - public final ModuleNameNode alias; // Factor up to ImportDecl - - public ImportModule(CommonTree source, ModuleNameNode modname, ModuleNameNode alias) - { - super(source); - this.modname = modname; - this.alias = alias; - } - - @Override - protected ImportModule copy() - { - return new ImportModule(this.source, this.modname, this.alias); - } - - @Override - public ImportModule clone(AstFactory af) - { - ModuleNameNode name = (ModuleNameNode) this.modname.clone(af); - ModuleNameNode alias = (ModuleNameNode) this.alias.clone(af); - return af.ImportModule(this.source, name, alias); - } - - public ImportModule reconstruct(ModuleNameNode modname, ModuleNameNode alias) // Factor up - { - ScribDel del = del(); - ImportModule im = new ImportModule(this.source, modname, alias); - im = (ImportModule) im.del(del); - return im; - } - - @Override - public ImportModule visitChildren(AstVisitor nv) throws ScribbleException - { - ModuleNameNode modname = (ModuleNameNode) visitChild(this.modname, nv); - ModuleNameNode alias = (isAliased()) ? (ModuleNameNode) visitChild(this.alias, nv) : null; - return reconstruct(modname, alias); - } - - @Override - public boolean isImportModule() - { - return true; - } - - @Override - public boolean isAliased() - { - return this.alias != null; - } - - /*@Override - public ModuleName getVisibleName() - { - return isAliased() ? getAlias() : this.modname.toName(); - }*/ - - @Override - public ModuleName getAlias() - { - return this.alias.toName(); - } - - @Override - public String toString() - { - String s = Constants.IMPORT_KW + " " + this.modname; - if (isAliased()) - { - s += " " + Constants.AS_KW + " " + this.alias; - } - return s + ";"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/InteractionNode.java b/scribble-core/src/main/java/org/scribble/ast/InteractionNode.java deleted file mode 100644 index 3bcdea11e..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/InteractionNode.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.type.kind.ProtocolKind; - -// Make a compound interaction subclass for choice/parallel etc? -public interface InteractionNode extends ProtocolKindNode -{ - //Set> collectMessageIds(); // Not worth implementing this homomorphically for every case except MessageTransfer, better to use visitChildren pattern - //Map> getEnablingMessages(); -} diff --git a/scribble-core/src/main/java/org/scribble/ast/InteractionSeq.java b/scribble-core/src/main/java/org/scribble/ast/InteractionSeq.java deleted file mode 100644 index eb0684a56..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/InteractionSeq.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.LinkedList; -import java.util.List; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.visit.AstVisitor; - -public abstract class InteractionSeq extends ScribNodeBase implements ProtocolKindNode -{ - private final List> inters; - - /*@SuppressWarnings("unchecked") - private final Function> cast = (n) -> (InteractionNode) n;*/ - - protected InteractionSeq(CommonTree source, List> inters) - { - super(source); - this.inters = inters; - } - - public abstract InteractionSeq reconstruct(List> ins); - - /*@SuppressWarnings("unchecked") - private final Function> KIND_CAST = (n) -> (ProtocolKindNode) n;*/ - - @Override - public ScribNode visitChildren(AstVisitor nv) throws ScribbleException - { - //List> actions = visitChildListWithStrictClassCheck(this, this.actions, nv); - //List> actions = visitChildListWithCastCheck(this, this.inters, nv, InteractionNode.class, getKind(), this.cast); // Maybe too strict (e.g. rec unfolding maybe shouldn't return the rec) - List> actions = new LinkedList<>(); - for (InteractionNode in : this.inters) - { - //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 - // FIXME: make a unit test for this - ScribNode visited = visitChild(in, nv); - if (visited instanceof InteractionSeq) - { - @SuppressWarnings("unchecked") - InteractionSeq tmp = (InteractionSeq) visited; - actions.addAll(tmp.inters); - } - else - { - @SuppressWarnings("unchecked") - InteractionNode tmp = (InteractionNode) visited; - actions.add(tmp); - } - } - return reconstruct(actions); - } - - public List> getInteractions() - { - return Collections.unmodifiableList(this.inters); - } - - public boolean isEmpty() - { - return this.inters.isEmpty(); - } - - @Override - public String toString() - { - return this.inters.stream().map((i) -> i.toString()).collect(Collectors.joining("\n")); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/Interrupt.java b/scribble-core/src/main/java/org/scribble/ast/Interrupt.java deleted file mode 100644 index cbedda019..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/Interrupt.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.name.simple.RoleNode; - -// Maybe factor out a base class with MessageTransfer (the list of dest roles has a different meaning though) -// Can't use abstract/reconstruct pattern, LocalInterrupt has different arguments -- add dummy dests field here to make reconstruct work? -public class Interrupt extends ScribNodeBase//AbstractSimpleInteractionNode -{ - public final RoleNode src; - private final List msgs; - - protected Interrupt(CommonTree source, RoleNode src, List msgs) - { - super(source); - this.src = src; - this.msgs = new LinkedList<>(msgs); - } - - @Override - protected ScribNodeBase copy() - { - // TODO Auto-generated method stub - throw new RuntimeException("TODO: " + this); - } - - @Override - public Interrupt clone(AstFactory af) - { - // TODO Auto-generated method stub - throw new RuntimeException("TODO: " + this); - } - - public List getMessages() - { - return this.msgs; - } - - //protected abstract Interrupt reconstruct(CommonTree ct, RoleNode src, List msgs, GlobalInterruptContext ncontext, Env env); - - /*@Override - public Interrupt leaveWFChoiceCheck(WellFormedChoiceChecker checker) throws ScribbleException - { - Role src = this.src.toName(); - WellFormedChoiceEnv env = checker.getEnv(); - for (Message msg : this.msgs.stream().map((mn) -> mn.toMessage()).collect(Collectors.toList())) - { - for (Role dest : ((GlobalInterruptContext) getContext()).getDestinations()) - { - // Recorded in the interruptible env (not the block or the parent) - //checker.setEnv(checker.getEnv().addInterrupt(src, dest, msg.toScopedMessage(checker.getScope()))); // No: src must be enabled, and if receiver may be enabled by this interrupt then it must also be receiving normally inside the interruptible block - //checker.getEnv().addMessage(src, dest, msg); - env = env.addInterrupt(src, dest, msg.toScopedMessage(checker.getScope())); - } - } - checker.setEnv(env); - return this; - } - - /*@Override - public Interrupt leave(EnvVisitor nv) throws ScribbleException - { - Interrupt gi = (Interrupt) super.leave(nv); - Env env = nv.getEnv(); - Role src = gi.src.toName(); - List tmp = new LinkedList<>(gi.dests); // For GlobalInterrupt, won't work till after well-formedness checked - tmp.remove(src); - for (MessageNode msg : this.msgs) - { - for (Role dest : tmp) - { - env.ops.addOperator(src, dest, msg.getOperator()); - } - } - return gi; - } - - @Override - public Interrupt substitute(Substitutor subs) throws ScribbleException - { - // Follows GlobalMessageTransfer - RoleNode src = subs.substituteRole(this.src.toName()); - List msgs = new LinkedList<>(); - for (MessageNode msg : this.msgs) - { - if (msg.isParameterNode()) - { - msgs.add((MessageNode) subs.substituteParameter(((ParameterNode) msg).toName())); - } - else - { - msgs.add((MessageNode) subs.visit((AbstractNode) msg)); - } - } - List dests = new LinkedList<>(); - for (Role dest : this.dests) - { - dests.add(subs.substituteRole(dest).toName()); - } - return new Interrupt(this.ct, src, msgs, dests); - }* / - - @Override - public Interrupt visitChildren(NodeVisitor nv) throws ScribbleException - { - RoleNode src = (RoleNode) visitChild(this.src, nv); - List msgs = new LinkedList<>(); - for (MessageNode msg : this.msgs) - { - //msgs.add(MessageTransfer.visitMessageNode(nv, msg)); - msgs.add((MessageNode) visitChild(msg, nv)); - } - return new Interrupt(this.ct, src, msgs, getContext(), getEnv());//, this.dests); - //return reconstruct(this.ct, src, msgs, getContext(), getEnv()); - } - - @Override - public GlobalInterruptContext getContext() - { - return (GlobalInterruptContext) super.getContext(); - }*/ - - /*public List getOperators(Env env) - { - List ops = new LinkedList<>(); - for (MessageNode msg : this.msgs) - { - // FIXME: factor out scope prefix manipulation - ops.add(new Operator(env.scopes.getCurrentPrefix() + msg.getOperator().text)); - } - return ops; - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/Interruptible.java b/scribble-core/src/main/java/org/scribble/ast/Interruptible.java deleted file mode 100644 index 27cfee155..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/Interruptible.java +++ /dev/null @@ -1,128 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.name.simple.ScopeNode; -import org.scribble.type.kind.ProtocolKind; - -public abstract class Interruptible extends CompoundInteractionNode implements ScopedNode -{ - public final ScopeNode scope; - public final ProtocolBlock block; - public final List interrs; - - protected Interruptible(CommonTree source, ScopeNode scope, ProtocolBlock block, List interrs) - { - super(source); - this.scope = scope; - this.block = block; - this.interrs = Collections.unmodifiableList(interrs); - } - - /*protected abstract Interruptible reconstruct(CommonTree ct, ScopeNode scope, T1 block, List interrs, CompoundInteractionNodeContext icontext, Env env); - - @Override - public NodeContextBuilder enterContextBuilding(NodeContextBuilder builder) throws ScribbleException - { - builder.pushContext(new CompoundInteractionNodeContext()); - return builder; - } - - @Override - public Interruptible leaveContextBuilding(NodeContextBuilder builder) throws ScribbleException - { - CompoundInteractionNodeContext icontext = (CompoundInteractionNodeContext) builder.popContext(); - builder.replaceContext(((CompoundInteractionContext) builder.peekContext()).merge(icontext)); - icontext = (CompoundInteractionNodeContext) icontext.merge(this.block.getContext()); - //return new Interruptible(this.ct, this.scope, this.block, this.interrs, icontext); - return reconstruct(this.ct, this.scope, this.block, this.interrs, icontext, getEnv()); - } - - @Override - public Interruptible leaveWFChoiceCheck(WellFormedChoiceChecker checker) throws ScribbleException - { - checker.getEnv().leave(this, checker); - return this; - - /*Role src = this.src.toName(); - for (Message msg : this.msgs.stream().map((mn) -> mn.toMessage()).collect(Collectors.toList())) - { - for (Role dest : ((GlobalInterruptContext) getContext()).getDestinations()) - { - //checker.getEnv().addInterrupt(src, dest, msg); // No: src must be enabled, and if receiver may be enabled by this interrupt then it must also be receiving normally inside the interruptible block - - System.out.println("2a: " + src + ", " + dest + ", " + msg); - - checker.getEnv().addMessage(src, dest, msg); - } - }* / - } - - @Override - public Interruptible leaveReachabilityCheck(ReachabilityChecker checker) throws ScribbleException - { - checker.getEnv().leave(this, checker); - return this; - } - - @Override - public Interruptible visitChildren(NodeVisitor nv) throws ScribbleException - { - ScopeNode scope = this.scope; - if (scope != null) - { - scope = (ScopeNode) visitChild(this.scope, nv); - } - //ProtocolBlock> block = (ProtocolBlock>) nv.visit(this.block); - T1 block = visitChildWithClassCheck(this, this.block, nv); - List interrs = visitChildListWithClassCheck(this, this.interrs, nv); - //return new Interruptible<>(this.ct, scope, block, interrs, getContext(), getEnv()); - return reconstruct(this.ct, scope, block, interrs, getContext(), getEnv()); - } - - @Override - public boolean isEmptyScope() - { - return false; - } - - @Override - //public Scope getScope() - public SimpleName getScopeElement() - { - return this.scope.toName(); - }*/ - - public boolean isScopeNodeImplicit() - { - return this.scope == null; - } - - /*@Override - public String toString() - { - String s = Constants.INTERRUPTIBLE_KW + " "; - if (!isScopeNodeImplicit()) - { - s += this.scope + ": "; - } - s += this.block + " " + Constants.WITH_KW + " {\n"; - s += this.interrs.stream().map((i) -> i.toString()).collect(Collectors.joining("\n")) + "\n"; - return s + "}"; - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/MessageNode.java b/scribble-core/src/main/java/org/scribble/ast/MessageNode.java deleted file mode 100644 index 508c53060..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/MessageNode.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.type.Message; - -// A sig kind node: MessageSignatureNode, MessageSignatureNameNode or NonRoleParamNode -public interface MessageNode extends NonRoleArgNode -{ - Message toMessage(); - - MessageNode clone(AstFactory af); - - //Arg toArg(); // Not possible due to "diamond" with PayloadElemNameNode at AmbigNameNode - - MessageNode project(AstFactory af); // Not role sensitive // Factor into visitor/env pattern? Currently not -} diff --git a/scribble-core/src/main/java/org/scribble/ast/MessageSigNameDecl.java b/scribble-core/src/main/java/org/scribble/ast/MessageSigNameDecl.java deleted file mode 100644 index 25463d228..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/MessageSigNameDecl.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.qualified.MemberNameNode; -import org.scribble.ast.name.qualified.MessageSigNameNode; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.SigKind; -import org.scribble.type.name.MessageSigName; -import org.scribble.type.name.ModuleName; - -public class MessageSigNameDecl extends NonProtocolDecl -{ - public MessageSigNameDecl(CommonTree source, String schema, String extName, String extSource, MessageSigNameNode name) - { - super(source, schema, extName, extSource, name); - } - - @Override - protected MessageSigNameDecl copy() - { - return new MessageSigNameDecl(this.source, this.schema, this.extName, this.extSource, getNameNode()); - } - - @Override - public MessageSigNameDecl clone(AstFactory af) - { - MessageSigNameNode name = (MessageSigNameNode) this.name.clone(af); - return af.MessageSigNameDecl(this.source, this.schema, this.extName, this.extSource, name); - } - - @Override - public MessageSigNameDecl reconstruct(String schema, String extName, String extSource, MemberNameNode name) - { - ScribDel del = del(); - MessageSigNameDecl msnd = new MessageSigNameDecl(this.source, schema, extName, extSource, (MessageSigNameNode) name); - msnd = (MessageSigNameDecl) msnd.del(del); - return msnd; - } - - @Override - public boolean isMessageSigNameDecl() - { - return true; - } - - @Override - public MessageSigNameNode getNameNode() - { - return (MessageSigNameNode) super.getNameNode(); - } - - @Override - public MessageSigName getDeclName() - { - return (MessageSigName) super.getDeclName(); - } - - @Override - public MessageSigName getFullMemberName(Module mod) - { - ModuleName fullmodname = mod.getFullModuleName(); - return new MessageSigName(fullmodname, getDeclName()); - } - - @Override - public String toString() - { - return Constants.SIG_KW + " <" + this.schema + "> \"" + this.extName - + "\" " + Constants.FROM_KW + " \"" + this.extSource + "\" " - + Constants.AS_KW + " " + this.name + ";"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/MessageSigNode.java b/scribble-core/src/main/java/org/scribble/ast/MessageSigNode.java deleted file mode 100644 index 6eed9f625..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/MessageSigNode.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.simple.OpNode; -import org.scribble.del.ScribDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.MessageSig; -import org.scribble.visit.AstVisitor; - -public class MessageSigNode extends ScribNodeBase implements MessageNode -{ - public final OpNode op; - public final PayloadElemList payloads; - - public MessageSigNode(CommonTree source, OpNode op, PayloadElemList payload) - { - super(source); - this.op = op; - this.payloads = payload; - } - - @Override - public MessageNode project(AstFactory af) // Currently outside of visitor/env pattern - { - return af.MessageSigNode(this.source, this.op, this.payloads.project(af)); // Original del not retained by projection - } - - @Override - protected MessageSigNode copy() - { - return new MessageSigNode(this.source, this.op, this.payloads); - } - - @Override - public MessageSigNode clone(AstFactory af) - { - OpNode op = this.op.clone(af); - PayloadElemList payload = this.payloads.clone(af); - return af.MessageSigNode(this.source, op, payload); - } - - public MessageSigNode reconstruct(OpNode op, PayloadElemList payload) - { - ScribDel del = del(); - MessageSigNode msn = new MessageSigNode(this.source, op, payload); - msn = (MessageSigNode) msn.del(del); - return msn; - } - - @Override - public MessageSigNode visitChildren(AstVisitor nv) throws ScribbleException - { - OpNode op = (OpNode) visitChild(this.op, nv); - PayloadElemList payload = (PayloadElemList) visitChild(this.payloads, nv); - return reconstruct(op, payload); - } - - - @Override - public boolean isMessageSigNode() - { - return true; - } - - // Make a direct scoped version? (taking scope as argument) - @Override - public MessageSig toArg() - { - return new MessageSig(this.op.toName(), this.payloads.toPayload()); - } - - @Override - public MessageSig toMessage() - { - return toArg(); - } - - @Override - public String toString() - { - return this.op.toString() + this.payloads.toString(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/MessageTransfer.java b/scribble-core/src/main/java/org/scribble/ast/MessageTransfer.java deleted file mode 100644 index 626a3a77e..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/MessageTransfer.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.LinkedList; -import java.util.List; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.Role; -import org.scribble.visit.AstVisitor; - -public abstract class MessageTransfer extends SimpleInteractionNode -{ - public final RoleNode src; - public final MessageNode msg; // FIXME: ambig may get resolved to an unexpected kind, e.g. DataTypeNode (cf. DoArg, PayloadElem wrappers) - protected final List dests; - - protected MessageTransfer(CommonTree source, RoleNode src, MessageNode msg, List dests) - { - super(source); - this.src = src; - this.msg = msg; - this.dests = new LinkedList<>(dests); // FIXME: Collections.unmodifiable? - } - - public abstract MessageTransfer reconstruct(RoleNode src, MessageNode msg, List dests); - - @Override - public MessageTransfer visitChildren(AstVisitor nv) throws ScribbleException - { - RoleNode src = (RoleNode) visitChild(this.src, nv); - MessageNode msg = (MessageNode) visitChild(this.msg, nv); - List dests = visitChildListWithClassEqualityCheck(this, this.dests, nv); - return reconstruct(src, msg, dests); - } - - public List getDestinations() - { - return Collections.unmodifiableList(this.dests); - } - - public List getDestinationRoles() - { - return this.dests.stream().map((rn) -> rn.toName()).collect(Collectors.toList()); - } - - @Override - public abstract String toString(); -} diff --git a/scribble-core/src/main/java/org/scribble/ast/Module.java b/scribble-core/src/main/java/org/scribble/ast/Module.java deleted file mode 100644 index f5797acbd..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/Module.java +++ /dev/null @@ -1,222 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.LinkedList; -import java.util.List; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.global.GProtocolDecl; -import org.scribble.ast.local.LProtocolDecl; -import org.scribble.del.ScribDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.Global; -import org.scribble.type.kind.Kind; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.DataType; -import org.scribble.type.name.MessageSigName; -import org.scribble.type.name.ModuleName; -import org.scribble.type.name.ProtocolName; -import org.scribble.util.ScribUtil; -import org.scribble.visit.AstVisitor; - -public class Module extends ScribNodeBase -{ - public final ModuleDecl moddecl; - - // Using (implicitly bounded) nested wildcards for mixed element lists (better practice to use separate lists?) - private final List> imports; - private final List> data; - private final List> protos; - - public Module(CommonTree source, ModuleDecl moddecl, List> imports, - List> data, List> protos) - { - super(source); - this.moddecl = moddecl; - this.imports = new LinkedList<>(imports); - this.data = new LinkedList<>(data); - this.protos = new LinkedList<>(protos); - } - - @Override - protected Module copy() - { - return new Module(this.source, this.moddecl, this.imports, this.data, this.protos); - } - - @Override - public Module clone(AstFactory af) - { - ModuleDecl moddecl = (ModuleDecl) this.moddecl.clone(af); - List> imports = ScribUtil.cloneList(af, this.imports); - List> data = ScribUtil.cloneList(af, this.data); - List> protos = ScribUtil.cloneList(af, this.protos); - return af.Module(this.source, moddecl, imports, data, protos); - } - - public Module reconstruct(ModuleDecl moddecl, List> imports, List> data, List> protos) - { - ScribDel del = del(); - Module m = new Module(this.source, moddecl, imports, data, protos); - m = (Module) m.del(del); - return m; - } - - @Override - public Module visitChildren(AstVisitor nv) throws ScribbleException - { - ModuleDecl moddecl = (ModuleDecl) visitChild(this.moddecl, nv); - // class equality check probably too restrictive - List> imports = ScribNodeBase.visitChildListWithClassEqualityCheck(this, this.imports, nv); - List> data = ScribNodeBase.visitChildListWithClassEqualityCheck(this, this.data, nv); - List> protos = ScribNodeBase.visitChildListWithClassEqualityCheck(this, this.protos, nv); - return reconstruct(moddecl, imports, data, protos); - } - - public ModuleName getFullModuleName() - { - return this.moddecl.getFullModuleName(); - } - - @Override - public String toString() - { - String s = moddecl.toString(); - for (ImportDecl id : this.imports) - { - s += "\n" + id; - } - for (NonProtocolDecl dtd : this.data) - { - s += "\n" + dtd; - } - for (ProtocolDecl pd : this.protos) - { - s += "\n" + pd; - } - return s; - } - - // ptn simple alias name - public DataTypeDecl getDataTypeDecl(DataType simpname) // Simple name (as for getProtocolDecl) - { - for (NonProtocolDecl dtd : this.data) - { - if (dtd.isDataTypeDecl() && dtd.getDeclName().equals(simpname)) - { - return (DataTypeDecl) dtd; - } - } - throw new RuntimeException("Data type not found: " + simpname); - } - - // msn simple alias name - public MessageSigNameDecl getMessageSigDecl(MessageSigName simpname) - { - for (NonProtocolDecl dtd : this.data) - { - if (dtd instanceof MessageSigNameDecl && dtd.getDeclName().equals(simpname)) - { - return (MessageSigNameDecl) dtd; - } - } - throw new RuntimeException("Message signature not found: " + simpname); - } - - public List> getImportDecls() - { - return Collections.unmodifiableList(this.imports); - } - - public List> getNonProtocolDecls() - { - return Collections.unmodifiableList(this.data); - } - - public List> getProtocolDecls() - { - return Collections.unmodifiableList(this.protos); - } - - public List getGlobalProtocolDecls() - { - return getProtocolDecls(IS_GLOBALPROTOCOLDECL, TO_GLOBALPROTOCOLDECL); - } - - public List getLocalProtocolDecls() - { - return getProtocolDecls(IS_LOCALPROTOCOLDECL, TO_LOCALPROTOCOLDECL); - } - - private > - List getProtocolDecls(Predicate> filter, Function, T> cast) - { - return this.protos.stream().filter(filter).map(cast).collect(Collectors.toList()); - } - - public boolean hasProtocolDecl(ProtocolName simpname) - { - return hasProtocolDecl(this.protos, simpname); - } - - // pn is simple name - // separate into global/local? - public ProtocolDecl getProtocolDecl(ProtocolName simpname) - { - return getProtocolDecl(this.protos, simpname); - } - - private static - boolean hasProtocolDecl(List> pds, ProtocolName simpname) - { - return pds.stream() - .filter((pd) -> pd.header.getDeclName().equals(simpname) - && (simpname.getKind().equals(Global.KIND)) ? pd.isGlobal() : pd.isLocal()) - .count() > 0; - } - - // pn is simple name - private static - ProtocolDecl getProtocolDecl(List> pds, ProtocolName simpname) - { - List> filtered = pds.stream() - .filter((pd) -> pd.header.getDeclName().equals(simpname) - && (simpname.getKind().equals(Global.KIND)) ? pd.isGlobal() : pd.isLocal()) - .collect(Collectors.toList()); - if (filtered.size() == 0) - { - throw new RuntimeException("Protocol not found: " + simpname); - } - /*if (filtered.size() > 1) - { - throw new RuntimeException("Found duplicate protocol decls: " + simpname); // Just return first -- allows Do/DoArgListDel name disambiguation to go through, and later caught on leaving Module - }*/ - @SuppressWarnings("unchecked") - ProtocolDecl res = (ProtocolDecl) filtered.get(0); - return res; - } - - private static final Predicate> IS_GLOBALPROTOCOLDECL = (pd) -> pd.isGlobal(); - - private static final Predicate> IS_LOCALPROTOCOLDECL = (pd) -> pd.isLocal(); - - private static final Function , GProtocolDecl> TO_GLOBALPROTOCOLDECL = (pd) -> (GProtocolDecl) pd; - - private static final Function , LProtocolDecl> TO_LOCALPROTOCOLDECL = (pd) -> (LProtocolDecl) pd; -} diff --git a/scribble-core/src/main/java/org/scribble/ast/ModuleDecl.java b/scribble-core/src/main/java/org/scribble/ast/ModuleDecl.java deleted file mode 100644 index af963bd06..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/ModuleDecl.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.qualified.ModuleNameNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ModuleKind; -import org.scribble.type.name.ModuleName; -import org.scribble.visit.AstVisitor; - -public class ModuleDecl extends NameDeclNode -{ - public ModuleDecl(CommonTree source, ModuleNameNode fullmodname) - { - super(source, fullmodname); - } - - @Override - protected ModuleDecl copy() - { - return new ModuleDecl(this.source, (ModuleNameNode) this.name); - } - - @Override - public ModuleDecl clone(AstFactory af) - { - ModuleNameNode modname = (ModuleNameNode) this.name.clone(af); - return af.ModuleDecl(this.source, modname); - } - - @Override - public ModuleDecl visitChildren(AstVisitor nv) throws ScribbleException - { - ModuleNameNode fullmodname = (ModuleNameNode) visitChild(this.name, nv); - return nv.job.af.ModuleDecl(this.source, fullmodname); // cf., reconstruct - } - - @Override - public String toString() - { - return Constants.MODULE_KW + " " + this.name + ";"; - } - - @Override - public ModuleName getDeclName() - { - //return (ModuleName) super.getDeclName(); // Would return full name - return ((ModuleName) super.getDeclName()).getSimpleName(); // Uniform with other NameDeclNodes wrt. returning simple name - } - - public ModuleName getFullModuleName() - { - return (ModuleName) this.name.toName(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/NameDeclNode.java b/scribble-core/src/main/java/org/scribble/ast/NameDeclNode.java deleted file mode 100644 index 33e918aa0..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/NameDeclNode.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.NameNode; -import org.scribble.type.kind.Kind; -import org.scribble.type.name.Name; - -public abstract class NameDeclNode extends ScribNodeBase -{ - public final NameNode name; - - protected NameDeclNode(CommonTree source, NameNode name) - { - super(source); - this.name = name; - } - - public Name getDeclName() - { - return this.name.toName(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/NonProtocolDecl.java b/scribble-core/src/main/java/org/scribble/ast/NonProtocolDecl.java deleted file mode 100644 index 5226e3486..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/NonProtocolDecl.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.qualified.MemberNameNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.NonProtocolKind; -import org.scribble.type.name.MemberName; -import org.scribble.visit.AstVisitor; - -// Rename to something better -public abstract class NonProtocolDecl extends NameDeclNode implements ModuleMember -{ - public final String schema; - public final String extName; - public final String extSource; - - public NonProtocolDecl(CommonTree source, String schema, String extName, String extSource, MemberNameNode name) - { - super(source, name); - this.schema = schema; - this.extName = extName; - this.extSource = extSource; - } - - public abstract NonProtocolDecl reconstruct(String schema, String extName, String source, MemberNameNode name); - - @Override - public NonProtocolDecl visitChildren(AstVisitor nv) throws ScribbleException - { - MemberNameNode name = (MemberNameNode) visitChildWithClassEqualityCheck(this, this.name, nv); - return reconstruct(this.schema, this.extName, this.extSource, name); - } - - // Maybe should be moved to ModuleMember - public boolean isDataTypeDecl() - { - return false; - } - - public boolean isMessageSigNameDecl() - { - return false; - } - - public MemberNameNode getNameNode() - { - return (MemberNameNode) this.name; - } - - @Override - public MemberName getDeclName() - { - return (MemberName) super.getDeclName(); // Simple name -- not consistent with ModuleDecl - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/NonRoleArg.java b/scribble-core/src/main/java/org/scribble/ast/NonRoleArg.java deleted file mode 100644 index c2bac6d55..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/NonRoleArg.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.del.ScribDel; -import org.scribble.type.name.Role; - -public class NonRoleArg extends DoArg -{ - public NonRoleArg(CommonTree source, NonRoleArgNode arg) - { - super(source, arg); - } - - @Override - protected ScribNodeBase copy() - { - return new NonRoleArg(this.source, getVal()); - } - - @Override - public NonRoleArg clone(AstFactory af) - { - NonRoleArgNode arg = (NonRoleArgNode) getVal().clone(af); - return af.NonRoleArg(this.source, arg); - } - - @Override - public NonRoleArg reconstruct(NonRoleArgNode arg) - { - ScribDel del = del(); - NonRoleArg ai = new NonRoleArg(this.source, arg); - ai = (NonRoleArg) ai.del(del); - return ai; - } - - @Override - public NonRoleArgNode getVal() - { - return (NonRoleArgNode) super.getVal(); - } - - @Override - public NonRoleArg project(AstFactory af, Role self) - { - return af.NonRoleArg(this.source, getVal()); // arg needs projection? - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/NonRoleArgList.java b/scribble-core/src/main/java/org/scribble/ast/NonRoleArgList.java deleted file mode 100644 index 1278deedb..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/NonRoleArgList.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.del.ScribDel; -import org.scribble.type.Arg; -import org.scribble.type.kind.NonRoleArgKind; -import org.scribble.type.name.Role; -import org.scribble.util.ScribUtil; - -// Cf. NonRoleParamDeclList -public class NonRoleArgList extends DoArgList -{ - public NonRoleArgList(CommonTree source, List args) - { - super(source, args); - } - - @Override - protected ScribNodeBase copy() - { - return new NonRoleArgList(this.source, getDoArgs()); - } - - @Override - public NonRoleArgList clone(AstFactory af) - { - List args = ScribUtil.cloneList(af, getDoArgs()); - return af.NonRoleArgList(this.source, args); - } - - @Override - public DoArgList reconstruct(List instans) - { - ScribDel del = del(); - NonRoleArgList ail = new NonRoleArgList(this.source, instans); - ail = (NonRoleArgList) ail.del(del); - return ail; - } - - @Override - public NonRoleArgList project(AstFactory af, Role self) - { - List instans = - getDoArgs().stream().map(ai -> ai.project(af, self)).collect(Collectors.toList()); - return af.NonRoleArgList(this.source, instans); - } - - public boolean isEmpty() - { - return getDoArgs().isEmpty(); - } - - public List getArgumentNodes() - { - return getDoArgs().stream().map((ai) -> ai.val).collect(Collectors.toList()); - } - - public List> getArguments() - { - return getDoArgs().stream().map((ai) -> ai.val.toArg()).collect(Collectors.toList()); - } - - @Override - public String toString() - { - return (getDoArgs().isEmpty()) - ? "" - : "<" + super.toString() + ">"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/NonRoleParamDecl.java b/scribble-core/src/main/java/org/scribble/ast/NonRoleParamDecl.java deleted file mode 100644 index ea83c2b43..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/NonRoleParamDecl.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.simple.NonRoleParamNode; -import org.scribble.ast.name.simple.SimpleNameNode; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.DataTypeKind; -import org.scribble.type.kind.NonRoleParamKind; -import org.scribble.type.kind.SigKind; -import org.scribble.type.name.Role; - -public class NonRoleParamDecl extends HeaderParamDecl -{ - public final K kind; - - public NonRoleParamDecl(CommonTree source, K kind, NonRoleParamNode name) - { - super(source, name); - this.kind = kind; - } - - @Override - public NonRoleParamDecl clone(AstFactory af) - { - NonRoleParamNode param = (NonRoleParamNode) this.name.clone(af); - return af.NonRoleParamDecl(this.source, this.kind, param); - } - - @Override - public NonRoleParamDecl reconstruct(SimpleNameNode name) - { - ScribDel del = del(); - NonRoleParamDecl pd = new NonRoleParamDecl<>(this.source, this.kind, (NonRoleParamNode) name); - @SuppressWarnings("unchecked") - NonRoleParamDecl tmp = (NonRoleParamDecl) pd.del(del); - return tmp; - } - - @Override - protected NonRoleParamDecl copy() - { - return new NonRoleParamDecl<>(this.source, this.kind, (NonRoleParamNode) this.name); - } - - @Override - public NonRoleParamDecl project(AstFactory af, Role self) - { - NonRoleParamNode pn = af.NonRoleParamNode(this.name.source, this.kind, this.name.toString()); - return af.NonRoleParamDecl(this.source, this.kind, pn); - } - - @Override - public String getKeyword() - { - if (this.kind.equals(SigKind.KIND)) - { - return Constants.SIG_KW; - } - else if (this.kind.equals(DataTypeKind.KIND)) - { - return Constants.TYPE_KW; - } - else - { - throw new RuntimeException("Shouldn't get in here: " + this.kind); - } - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/NonRoleParamDeclList.java b/scribble-core/src/main/java/org/scribble/ast/NonRoleParamDeclList.java deleted file mode 100644 index 774f80164..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/NonRoleParamDeclList.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.NonRoleParamKind; -import org.scribble.type.name.Name; -import org.scribble.type.name.Role; -import org.scribble.util.ScribUtil; - -// 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 HeaderParamDeclList -{ - public NonRoleParamDeclList(CommonTree source, List> decls) - { - super(source, decls); - } - - @Override - protected NonRoleParamDeclList copy() - { - return new NonRoleParamDeclList(this.source, getDecls()); - } - - @Override - public NonRoleParamDeclList clone(AstFactory af) - { - List> decls = ScribUtil.cloneList(af, getDecls()); - return af.NonRoleParamDeclList(this.source, decls); - } - - @Override - public NonRoleParamDeclList reconstruct(List> decls) - { - ScribDel del = del(); - NonRoleParamDeclList rdl = new NonRoleParamDeclList(this.source, castParamDecls(decls)); - rdl = (NonRoleParamDeclList) rdl.del(del); - return rdl; - } - - @Override - public List> getDecls() - { - return castParamDecls(super.getDecls()); - } - - public List> getParameters() - { - return getDecls().stream().map((decl) -> decl.getDeclName()).collect(Collectors.toList()); - } - - // FIXME: move to delegate? - @Override - public NonRoleParamDeclList project(AstFactory af, Role self) - { - return af.NonRoleParamDeclList(this.source, getDecls()); - } - - @Override - public String toString() - { - return (isEmpty()) - ? "" - : "<" + super.toString() + ">"; - } - - private static List> - castParamDecls(List> decls) - { - return decls.stream().map((d) -> (NonRoleParamDecl) d).collect(Collectors.toList()); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/Parallel.java b/scribble-core/src/main/java/org/scribble/ast/Parallel.java deleted file mode 100644 index 9b9289829..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/Parallel.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.LinkedList; -import java.util.List; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.visit.AstVisitor; - -public abstract class Parallel extends CompoundInteractionNode -{ - private final List> blocks; - - protected Parallel(CommonTree source, List> blocks) - { - super(source); - this.blocks = new LinkedList<>(blocks); - } - - public abstract Parallel reconstruct(List> blocks); - - @Override - public Parallel visitChildren(AstVisitor nv) throws ScribbleException - { - List> blocks = visitChildListWithClassEqualityCheck(this, this.blocks, nv); - return reconstruct(blocks); - } - - public List> getBlocks() - { - return Collections.unmodifiableList(this.blocks); - } - - /*@Override - public NodeContextBuilder enterContextBuilding(NodeContextBuilder builder) throws ScribbleException - { - builder.pushContext(new CompoundInteractionNodeContext()); - return builder; - } - - @Override - public Parallel leaveContextBuilding(NodeContextBuilder builder) throws ScribbleException - { - CompoundInteractionNodeContext pcontext = (CompoundInteractionNodeContext) builder.popContext(); - List bcontexts = - this.blocks.stream().map((b) -> b.getContext()).collect(Collectors.toList()); - pcontext = (CompoundInteractionNodeContext) pcontext.merge(bcontexts); - builder.replaceContext(((CompoundInteractionContext) builder.peekContext()).merge(pcontext)); - //return new Parallel<>(this.ct, this.blocks, pcontext); - return reconstruct(this.ct, this.blocks, pcontext, getEnv()); - } - - @Override - public Parallel leaveWFChoiceCheck(WellFormedChoiceChecker checker) throws ScribbleException - { - checker.getEnv().leave(this, checker); - return this; - } - - @Override - public Parallel leaveReachabilityCheck(ReachabilityChecker checker) throws ScribbleException - { - checker.getEnv().leave(this, checker); - return this; - } - - /*@Override - public Parallel checkWellFormedness(WellFormednessChecker wfc) throws ScribbleException - {k - return visitWithEnv(wfc); - } - - @Override - public Parallel project(Projector proj) throws ScribbleException - { - return visitWithEnv(proj); - } - - @Override - public Parallel checkReachability(ReachabilityChecker rc) throws ScribbleException - { - return visitWithEnv(rc); - } - - public Parallel visitWithEnv(EnvVisitor nv) throws ScribbleException - { - Env env = nv.getEnv(); - List blocks = new LinkedList<>(); - for (ProtocolBlock block : this.blocks) - { - nv.setEnv(new Env(env)); - ProtocolBlock visited = (ProtocolBlock) nv.visit(block); - blocks.add(visited); - } - nv.setEnv(env); - return new Parallel(this.ct, blocks); - }*/ - - /*@Override - public String toString() - { - String sep = " " + Constants.AND_KW + " "; - return Constants.PAR_KW + " " - + this.blocks.stream().map((block) -> block.toString()).collect(Collectors.joining(sep)); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/PayloadElem.java b/scribble-core/src/main/java/org/scribble/ast/PayloadElem.java deleted file mode 100644 index 5d19851bf..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/PayloadElem.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.type.kind.PayloadTypeKind; -import org.scribble.type.name.PayloadElemType; - -// Not in grammar file -- but cf. DoArg (and PayloadElemList cf. DoArgList) -- i.e. need a wrapper for mixed and initially ambiguous name kinds -//public abstract class PayloadElem extends ScribNodeBase -//public abstract class PayloadElem> extends ScribNodeBase -- problem is GProtocolNameNode child isn't a payload kind, and anyway there's also a role node child -//public abstract class PayloadElem extends ScribNodeBase -//public interface PayloadElem extends ScribNode -public interface PayloadElem extends ScribNode -{ - PayloadElem project(AstFactory af); // Currently outside of visitor/env pattern (cf. MessageNode) - - default boolean isGlobalDelegationElem() - { - return false; - } - - default boolean isLocalDelegationElem() - { - return false; - } - - /*public final PayloadElemNameNode name; // Doesn't work for DelegationElem (Global@Role), name is global but payloadelem is local -- similar reason why not a NameNode, delegation doesn't fit -- would work for direct LProtocolNameNode elems though - - public PayloadElem(PayloadElemNameNode name) - { - this.name = name; - }*/ - - /*@Override - protected PayloadElem copy() - { - return new PayloadElem(this.name); - } - - @Override - public PayloadElem clone() - { - PayloadElemNameNode name = (PayloadElemNameNode) this.name.clone(); - return AstFactoryImpl.FACTORY.PayloadElem(name); - }*/ - - /*public PayloadElem reconstruct(PayloadElemNameNode name) - { - ScribDel del = del(); - PayloadElem elem = new PayloadElem(name); - elem = (PayloadElem) elem.del(del); - return elem; - } - - @Override - public PayloadElem visitChildren(AstVisitor nv) throws ScribbleException - { - PayloadElemNameNode name = (PayloadElemNameNode) visitChild(this.name, nv); - return reconstruct(name); - }*/ - - //public abstract PayloadType toPayloadType(); - public PayloadElemType toPayloadType(); // Mainly a wrapper method for the wrapped NameNode - - /*public abstract Name toName(); // Not deriving from Named/NameNode, delegation doesn't fit -- would need to make a special (Global@Role) name of Local kind - - @Override - public String toString() - { - //return this.name.toString(); - return toName().toString(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/PayloadElemList.java b/scribble-core/src/main/java/org/scribble/ast/PayloadElemList.java deleted file mode 100644 index d6ba1fcce..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/PayloadElemList.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.LinkedList; -import java.util.List; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.del.ScribDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.Payload; -import org.scribble.type.name.PayloadElemType; -import org.scribble.util.ScribUtil; -import org.scribble.visit.AstVisitor; - -// Cf. DoArgList, but here we don't need as much abstraction (cf. RoleArgList, NonRoleArgList) -public class PayloadElemList extends ScribNodeBase -{ - //private final List elems; // FIXME: parameterise on Kind (cf. sesstypes) - private final List> elems; - - //public PayloadElemList(List elems) - public PayloadElemList(CommonTree source, List> elems) - { - super(source); - this.elems = new LinkedList<>(elems); - } - - protected PayloadElemList project(AstFactory af) - { - return af.PayloadElemList(this.source, this.elems.stream().map(pe -> pe.project(af)).collect(Collectors.toList())); - } - - @Override - protected PayloadElemList copy() - { - return new PayloadElemList(this.source, this.elems); - } - - @Override - public PayloadElemList clone(AstFactory af) - { - //List elems = ScribUtil.cloneList(this.elems); - List> elems = ScribUtil.cloneList(af, this.elems); - return af.PayloadElemList(this.source, elems); - } - - //protected PayloadElemList reconstruct(List elems) - protected PayloadElemList reconstruct(List> elems) - { - ScribDel del = del(); - PayloadElemList pel = new PayloadElemList(this.source, elems); - pel = (PayloadElemList) pel.del(del); - return pel; - } - - @Override - public PayloadElemList visitChildren(AstVisitor nv) throws ScribbleException - { - //List elems = visitChildListWithClassEqualityCheck(this, this.elems, nv); - List> elems = visitChildListWithClassEqualityCheck(this, this.elems, nv); - return reconstruct(elems); - } - - //public List getElements() - public List> getElements() - { - return Collections.unmodifiableList(this.elems); - } - - public Payload toPayload() - { - //List> pts = this.elems.stream().map((pe) -> pe.name.toPayloadType()).collect(Collectors.toList()); - List> pts = this.elems.stream().map((pe) -> pe.toPayloadType()).collect(Collectors.toList()); - return new Payload(pts); - } - - public boolean isEmpty() - { - return this.elems.isEmpty(); - } - - @Override - public String toString() - { - return "(" + this.elems.stream().map((pe) -> pe.toString()).collect(Collectors.joining(", " )) + ")"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/ProtocolBlock.java b/scribble-core/src/main/java/org/scribble/ast/ProtocolBlock.java deleted file mode 100644 index 8b1ae830d..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/ProtocolBlock.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.visit.AstVisitor; - -public abstract class ProtocolBlock extends CompoundInteraction implements ProtocolKindNode -{ - public final InteractionSeq seq; - - public ProtocolBlock(CommonTree source, InteractionSeq seq) - { - super(source); - this.seq = seq; - } - - @Override - public abstract ProtocolBlock clone(AstFactory af); - - public abstract ProtocolBlock reconstruct(InteractionSeq seq); - - public abstract InteractionSeq getInteractionSeq(); - - @Override - public ProtocolBlock visitChildren(AstVisitor nv) throws ScribbleException - { - InteractionSeq seq = visitChildWithClassEqualityCheck(this, this.seq, nv); - return reconstruct(seq); - } - - public boolean isEmpty() - { - return this.seq.isEmpty(); - } - - @Override - public String toString() - { - return "{\n" + this.seq + "\n}"; // Empty block will contain an blank line - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/ProtocolDecl.java b/scribble-core/src/main/java/org/scribble/ast/ProtocolDecl.java deleted file mode 100644 index d967bd3fd..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/ProtocolDecl.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 org.antlr.runtime.tree.CommonTree; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.visit.AstVisitor; - -// FIXME: visitChildren for modifiers -public abstract class ProtocolDecl extends ScribNodeBase implements ModuleMember, ProtocolKindNode -{ - public static enum Modifiers { EXPLICIT, AUX } // FIXME: factor out? Header? - - // FIXME: lookup routines, e.g. isExplicit - public final List modifiers; - - // Maybe just use standard pattern, make private with casting getters -- works better (e.g. to use overridden getName) - public final ProtocolHeader header; - public final ProtocolDef def; - - protected ProtocolDecl(CommonTree source, List modifiers, ProtocolHeader header, ProtocolDef def) - { - super(source); - this.modifiers = Collections.unmodifiableList(modifiers); - this.header = header; - this.def = def; - } - - public abstract ProtocolDecl reconstruct(ProtocolHeader header, ProtocolDef def);//, ProtocolDeclContext pdcontext, Env env); - - @Override - public ProtocolDecl visitChildren(AstVisitor nv) throws ScribbleException - { - ProtocolHeader header = visitChildWithClassEqualityCheck(this, this.header, nv); - ProtocolDef def = visitChildWithClassEqualityCheck(this, this.def, nv); - return reconstruct(header, def); - } - - public abstract ProtocolHeader getHeader(); - public abstract ProtocolDef getDef(); - - //public abstract ProtocolName getFullProtocolName(Module mod); - - @Override - public String toString() - { - return this.header + " " + this.def; - } - - public boolean isExplicitModifier() - { - return this.modifiers.contains(Modifiers.EXPLICIT); - } - - public boolean isAuxModifier() - { - return this.modifiers.contains(Modifiers.AUX); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/ProtocolDef.java b/scribble-core/src/main/java/org/scribble/ast/ProtocolDef.java deleted file mode 100644 index 7df959ccc..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/ProtocolDef.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.visit.AstVisitor; - -public abstract class ProtocolDef extends ScribNodeBase implements ProtocolKindNode -{ - public final ProtocolBlock block; - - protected ProtocolDef(CommonTree source, ProtocolBlock block) - { - super(source); - this.block = block; - } - - public abstract ProtocolDef reconstruct(ProtocolBlock block); - - public abstract ProtocolBlock getBlock(); - - @Override - public ProtocolDef visitChildren(AstVisitor nv) throws ScribbleException - { - ProtocolBlock block = visitChildWithClassEqualityCheck(this, this.block, nv); - return reconstruct(block); - } - - @Override - public String toString() - { - return this.block.toString(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/ProtocolHeader.java b/scribble-core/src/main/java/org/scribble/ast/ProtocolHeader.java deleted file mode 100644 index 01e60bc27..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/ProtocolHeader.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.NameNode; -import org.scribble.ast.name.qualified.ProtocolNameNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.ProtocolName; -import org.scribble.visit.AstVisitor; - -// TODO: parameterize on global/local name node and role decl list (i.e. self roles) -public abstract class ProtocolHeader extends NameDeclNode implements ProtocolKindNode -{ - public final RoleDeclList roledecls; - public final NonRoleParamDeclList paramdecls; - - protected ProtocolHeader(CommonTree source, NameNode name, RoleDeclList roledecls, NonRoleParamDeclList paramdecls) - { - super(source, name); - this.roledecls = roledecls; - this.paramdecls = paramdecls; - } - - public abstract ProtocolHeader reconstruct(ProtocolNameNode name, RoleDeclList rdl, NonRoleParamDeclList pdl); - - @Override - public ProtocolHeader visitChildren(AstVisitor nv) throws ScribbleException - { - RoleDeclList rdl = (RoleDeclList) visitChild(this.roledecls, nv); - NonRoleParamDeclList pdl = (NonRoleParamDeclList) visitChild(this.paramdecls, nv); - return reconstruct((ProtocolNameNode) this.name, rdl, pdl); - } - - public boolean isParameterDeclListEmpty() - { - return this.paramdecls.isEmpty(); - } - - public abstract ProtocolNameNode getNameNode(); - - @Override - public ProtocolName getDeclName() - { - return (ProtocolName) super.getDeclName(); - } - - @Override - public String toString() - { - String s = Constants.PROTOCOL_KW + " " + this.name; - if (!isParameterDeclListEmpty()) - { - s += this.paramdecls; - } - return s + this.roledecls; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/ProtocolKindNode.java b/scribble-core/src/main/java/org/scribble/ast/ProtocolKindNode.java deleted file mode 100644 index 824cf9eda..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/ProtocolKindNode.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.type.kind.ProtocolKind; - -public interface ProtocolKindNode extends ScribNode -{ - default boolean isGlobal() - { - return false; - } - - default boolean isLocal() - { - return false; - } - - K getKind(); -} diff --git a/scribble-core/src/main/java/org/scribble/ast/Recursion.java b/scribble-core/src/main/java/org/scribble/ast/Recursion.java deleted file mode 100644 index f757c381e..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/Recursion.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.visit.AstVisitor; - -public abstract class Recursion extends CompoundInteractionNode -{ - public final RecVarNode recvar; - public final ProtocolBlock block; - - protected Recursion(CommonTree source, RecVarNode recvar, ProtocolBlock block) - { - super(source); - this.recvar = recvar; - this.block = block; - } - - public abstract Recursion reconstruct(RecVarNode recvar, ProtocolBlock block); - - @Override - public abstract Recursion clone(AstFactory af); - - @Override - public Recursion visitChildren(AstVisitor nv) throws ScribbleException - { - RecVarNode recvar = (RecVarNode) visitChild(this.recvar, nv); - ProtocolBlock block = visitChildWithClassEqualityCheck(this, this.block, nv); - return reconstruct(recvar, block); - } - - public abstract ProtocolBlock getBlock(); - - @Override - public String toString() - { - return Constants.REC_KW + " " + this.recvar + " " + this.block; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/RoleArg.java b/scribble-core/src/main/java/org/scribble/ast/RoleArg.java deleted file mode 100644 index c21472f23..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/RoleArg.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.RoleKind; -import org.scribble.type.name.Role; - -public class RoleArg extends DoArg -{ - public RoleArg(CommonTree source, RoleNode arg) - { - super(source, arg); - } - - @Override - protected ScribNodeBase copy() - { - return new RoleArg(this.source, getVal()); - } - - @Override - public RoleArg clone(AstFactory af) - { - RoleNode role = getVal().clone(af); - return af.RoleArg(this.source, role); - } - - @Override - public RoleArg reconstruct(RoleNode arg) - { - ScribDel del = del(); - RoleArg ri = new RoleArg(this.source, arg); - ri = (RoleArg) ri.del(del); - return ri; - } - - @Override - public RoleNode getVal() - { - return (RoleNode) super.getVal(); - } - - // FIXME: move to delegate? - @Override - public RoleArg project(AstFactory af, Role self) - { - RoleNode rn = (RoleNode) af.SimpleNameNode(this.val.source, RoleKind.KIND, this.val.toName().toString()); - return af.RoleArg(this.source, rn); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/RoleArgList.java b/scribble-core/src/main/java/org/scribble/ast/RoleArgList.java deleted file mode 100644 index b398ab562..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/RoleArgList.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.del.ScribDel; -import org.scribble.type.name.Role; -import org.scribble.util.ScribUtil; - -public class RoleArgList extends DoArgList -{ - public RoleArgList(CommonTree source, List roles) - { - super(source, roles); - } - - @Override - protected RoleArgList copy() - { - return new RoleArgList(this.source, getDoArgs()); - } - - @Override - public RoleArgList clone(AstFactory af) - { - List roles = ScribUtil.cloneList(af, getDoArgs()); - return af.RoleArgList(this.source, roles); - } - - @Override - public RoleArgList reconstruct(List roles) - { - ScribDel del = del(); - RoleArgList rl = new RoleArgList(this.source, roles); - rl = (RoleArgList) rl.del(del); - return rl; - } - - // Move to delegate? - @Override - public RoleArgList project(AstFactory af, Role self) - { - List instans = - getDoArgs().stream().map(ri -> ri.project(af, self)).collect(Collectors.toList()); - return af.RoleArgList(this.source, instans); - } - - // The role arguments - public List getRoles() - { - return getDoArgs().stream().map((ri) -> ri.val.toName()).collect(Collectors.toList()); - } - - @Override - public String toString() - { - return "(" + super.toString() + ")"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/RoleDecl.java b/scribble-core/src/main/java/org/scribble/ast/RoleDecl.java deleted file mode 100644 index a1b60d183..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/RoleDecl.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.ast.name.simple.SimpleNameNode; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.RoleKind; -import org.scribble.type.name.Name; -import org.scribble.type.name.Role; - -public class RoleDecl extends HeaderParamDecl -{ - public RoleDecl(CommonTree source, RoleNode name) - { - super(source, name); - } - - @Override - protected RoleDecl copy() - { - return new RoleDecl(this.source, (RoleNode) this.name); - } - - @Override - public RoleDecl clone(AstFactory af) - { - RoleNode role = (RoleNode) this.name.clone(af); - return af.RoleDecl(this.source, role); - } - - @Override - public RoleDecl reconstruct(SimpleNameNode name) - { - ScribDel del = del(); - RoleDecl rd = new RoleDecl(this.source, (RoleNode) name); - rd = (RoleDecl) rd.del(del); - return rd; - } - - @Override - public RoleDecl project(AstFactory af, Role self) - { - Name role = this.name.toName(); - RoleNode rn = (RoleNode) af.SimpleNameNode(this.name.source, RoleKind.KIND, role.toString()); - if (role.equals(self)) - { - return af.SelfRoleDecl(this.name.source, rn); - } - return af.RoleDecl(this.source, rn); - } - - @Override - public Role getDeclName() - { - return (Role) super.getDeclName(); - } - - public boolean isSelfRoleDecl() - { - return false; - } - - @Override - public String getKeyword() - { - return Constants.ROLE_KW; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/RoleDeclList.java b/scribble-core/src/main/java/org/scribble/ast/RoleDeclList.java deleted file mode 100644 index 74d273895..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/RoleDeclList.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.RoleKind; -import org.scribble.type.name.Role; -import org.scribble.util.ScribUtil; - -public class RoleDeclList extends HeaderParamDeclList -{ - public RoleDeclList(CommonTree source, List decls) - { - super(source, decls); - } - - @Override - protected RoleDeclList copy() - { - return new RoleDeclList(this.source, getDecls()); - } - - @Override - public RoleDeclList clone(AstFactory af) - { - List decls = ScribUtil.cloneList(af, getDecls()); - return af.RoleDeclList(this.source, decls); - } - - @Override - public HeaderParamDeclList reconstruct(List> decls) - { - ScribDel del = del(); - RoleDeclList rdl = new RoleDeclList(this.source, castRoleDecls(decls)); - rdl = (RoleDeclList) rdl.del(del); - return rdl; - } - - @Override - public List getDecls() - { - return castRoleDecls(super.getDecls()); - } - - public List getRoles() - { - return getDecls().stream().map((decl) -> decl.getDeclName()).collect(Collectors.toList()); - } - - // Move to del? - @Override - public RoleDeclList project(AstFactory af, Role self) - { - return af.RoleDeclList(this.source, getDecls()); - } - - @Override - public String toString() - { - return "(" + super.toString() + ")"; - } - - private static List castRoleDecls(List> decls) - { - return decls.stream().map((d) -> (RoleDecl) d).collect(Collectors.toList()); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/ScopedNode.java b/scribble-core/src/main/java/org/scribble/ast/ScopedNode.java deleted file mode 100644 index 7d5c50928..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/ScopedNode.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.type.kind.ScopeKind; -import org.scribble.type.name.Name; - -// Move to types? uniform with Named -public interface ScopedNode -{ - boolean isEmptyScope(); // false for interruptible (can be implicit but not empty) - - //Scope getScope(); - //String getScopeElement(); - - // SimpleName for Scope "elements" (Scope is a compound name with prefix) - //SimpleName getScopeElement(); // Distinguish simple and compound scope names? (as name kinds) - Name getScopeElement(); // Distinguish simple and compound scope names? (as name kinds) -} diff --git a/scribble-core/src/main/java/org/scribble/ast/ScribNode.java b/scribble-core/src/main/java/org/scribble/ast/ScribNode.java deleted file mode 100644 index d0e06e0af..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/ScribNode.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.del.ScribDel; -import org.scribble.main.ScribbleException; -import org.scribble.visit.AstVisitor; -import org.scribble.visit.Substitutor; - -/** - * This is the generic object from which all Scribble model objects - * are derived. - */ -public interface ScribNode -{ - // Returns a deep clone but with fresh dels (i.e. dels not copied) -- use the af to build with fresh dels - // i.e. recursively using AstFactory to rebuild the whole subtree - // Cf. node specific reconstructs, retain (i.e. share) the existing del -- so dels must be immutable (except for Envs) - ScribNode clone(AstFactory af); - - ScribDel del(); - ScribNode del(ScribDel del); - - ScribNode accept(AstVisitor nv) throws ScribbleException; - ScribNode visitChildren(AstVisitor nv) throws ScribbleException; - - // Simple operations, not worth doing del enter/leave pattern for - // Rely on visitChildren reconstruction pattern to do recursive reconstruction - ScribNode substituteNames(Substitutor subs); - // Cf. LInteractionNode.inferLocalChoiceSubject - - CommonTree getSource(); - // Previously: for parsed entities, null if not parsed - // Now: for the original parsed entity for error blaming; should not be null unless a "purely generated" entity -} diff --git a/scribble-core/src/main/java/org/scribble/ast/ScribNodeBase.java b/scribble-core/src/main/java/org/scribble/ast/ScribNodeBase.java deleted file mode 100644 index c8e4d0c4e..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/ScribNodeBase.java +++ /dev/null @@ -1,186 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.function.Function; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.del.ScribDel; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.Global; -import org.scribble.type.kind.Local; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.util.ScribUtil; -import org.scribble.visit.AstVisitor; -import org.scribble.visit.Substitutor; - -/** - * This is the generic object from which all Scribble model objects - * are derived. - */ -public abstract class ScribNodeBase implements ScribNode -{ - protected final CommonTree source; // Consequently, core depends on Antlr - // Used to be for parsed entities; null if not parsed - // Now: for the original parsed entity for error blaming; should not be null unless a purely generated entity - - protected ScribDel del; - - protected ScribNodeBase(CommonTree source) - { - this.source = source; - } - - @Override - public final CommonTree getSource() - { - return this.source; - } - - // 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 - protected abstract ScribNodeBase copy(); - - // Deep clone - @Override - public abstract ScribNodeBase clone(AstFactory af); - - @Override - public final ScribDel del() - { - return this.del; - } - - @Override - public final ScribNodeBase del(ScribDel del) - { - ScribNodeBase copy = copy(); - copy.del = del; - return copy; - } - - @Override - public ScribNode accept(AstVisitor nv) throws ScribbleException - { - return nv.visit(null, this); - } - - @Override - public ScribNode visitChildren(AstVisitor nv) throws ScribbleException - { - return this; - } - - protected ScribNode visitChild(ScribNode child, AstVisitor nv) throws ScribbleException - { - return nv.visit(this, child); - } - - public static final T del(T n, ScribDel del) - { - ScribNodeBase copy = ((ScribNodeBase) n).copy(); - copy.del = del; - return ScribUtil.castNodeByClass(n, copy); - } - - @Override - public ScribNode substituteNames(Substitutor subs) - { - return this; - } - - // 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 nv) throws ScribbleException - { - ScribNode visited = ((ScribNodeBase) parent).visitChild(child, nv); - // Same subtyping flexibility as standard cast - return ScribUtil.checkNodeClassEquality(child, visited); - } - - protected final static - List visitChildListWithClassEqualityCheck(ScribNode parent, List children, AstVisitor nv) - throws ScribbleException - { - return visitChildListWith(parent, children, nv, - (T t) -> ScribUtil.handleLambdaScribbleException( - () -> ScribNodeBase.visitChildWithClassEqualityCheck(parent, t, nv))); // -> 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 ScribbleException - { - /*List visited = new LinkedList<>(); - for (T n : children) - { - visited.add(c.call()); - } - return visited;*/ - // Maybe this exception hack is not worth it? Better to throw directly as ScribbleException - try - { - return children.stream().map(n -> c.apply(n)).collect(Collectors.toList()); - } - catch (RuntimeScribbleException rse) - { - Throwable cause = rse.getCause(); - if (cause instanceof ScribbleException) - { - throw (ScribbleException) 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 ProtocolKind, R extends ProtocolKindNode> - R visitProtocolKindChildWithCastCheck( - ScribNode parent, ScribNode child, AstVisitor nv, Class clazz, K kind, Function cast) - throws ScribbleException - { - ScribNode visited = ((ScribNodeBase) parent).visitChild(child, nv); - if (!clazz.isAssignableFrom(visited.getClass())) - { - throw new RuntimeException(nv.getClass() + " generic visit error: " + clazz + ", " + visited.getClass()); - } - ProtocolKindNode pkn = (ProtocolKindNode) 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 ProtocolKind, R extends ProtocolKindNode> - List visitProtocolKindChildListWithCastCheck( - ScribNode parent, List children, AstVisitor nv, Class c, K k, Function f) - throws ScribbleException - { - return visitChildListWith(parent, children, nv, - (T t) -> ScribUtil.handleLambdaScribbleException( - () -> ScribNodeBase.visitProtocolKindChildWithCastCheck(parent, t, nv, c, k, f))); // -> R - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/SimpleInteractionNode.java b/scribble-core/src/main/java/org/scribble/ast/SimpleInteractionNode.java deleted file mode 100644 index fa6a10c69..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/SimpleInteractionNode.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.type.kind.ProtocolKind; - -// Name should be read (Simple ( InteractionNode )) -public abstract class SimpleInteractionNode - extends ScribNodeBase implements InteractionNode -{ - protected SimpleInteractionNode(CommonTree source) - { - super(source); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/UnaryPayloadElem.java b/scribble-core/src/main/java/org/scribble/ast/UnaryPayloadElem.java deleted file mode 100644 index 40e8d31e2..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/UnaryPayloadElem.java +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.PayloadElemNameNode; -import org.scribble.del.ScribDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.PayloadTypeKind; -import org.scribble.type.name.PayloadElemType; -import org.scribble.util.ScribUtil; -import org.scribble.visit.AstVisitor; - - -// FIXME: make abstract, and make a DataTypeElem subclass with DataTypeKind parameter instance (alongside LDelegationElem) - -// 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 UnaryPayloadElem extends ScribNodeBase implements PayloadElem//extends PayloadElem -{ - //public final PayloadElemNameNode name; - //public final DataTypeNode data; - public final PayloadElemNameNode name; // (Ambig.) DataTypeNode or parameter - - //public DataTypeElem(PayloadElemNameNode name) - //public UnaryPayloadlem(DataTypeNode data) - //public UnaryPayloadElem(PayloadElemNameNode name) - public UnaryPayloadElem(CommonTree source, PayloadElemNameNode name) - { - //super(name); - //this.data = data; - super(source); - this.name = name; - } - - @Override - public UnaryPayloadElem project(AstFactory af) - { - return this; - } - - @Override - protected UnaryPayloadElem copy() - { - //return new UnaryPayloadElem(this.data); - return new UnaryPayloadElem<>(this.source, this.name); - } - - @Override - public UnaryPayloadElem clone(AstFactory af) - { - //PayloadElemNameNode name = (PayloadElemNameNode) this.data.clone(); // FIXME: make a DataTypeNameNode - //PayloadElemNameNode name = (PayloadElemNameNode) this.name.clone(); - PayloadElemNameNode name = ScribUtil.checkNodeClassEquality(this.name, this.name.clone(af)); - return af.UnaryPayloadElem(this.source, name); - } - - //public DataTypeElem reconstruct(PayloadElemNameNode name) - //public UnaryPayloadElem reconstruct(DataTypeNode name) - public UnaryPayloadElem reconstruct(PayloadElemNameNode name) - { - ScribDel del = del(); - UnaryPayloadElem elem = new UnaryPayloadElem<>(this.source, name); - elem = ScribNodeBase.del(elem, del); - return elem; - } - - @Override - public UnaryPayloadElem visitChildren(AstVisitor nv) throws ScribbleException - { - //PayloadElemNameNode name = (PayloadElemNameNode) visitChild(this.data, nv); - //DataTypeNode name = (PayloadElemNameNode) visitChild(this.data, nv); - @SuppressWarnings("unchecked") - PayloadElemNameNode name = (PayloadElemNameNode) visitChild(this.name, nv); - // FIXME: probably need to record an explicit kind token, for "cast checking" - // Cannot use ScribNodeBase.visitChildWithCastCheck because this is not a ProtocolKindNode - //PayloadElemNameNode name = (PayloadElemNameNode) visitChildWithClassEqualityCheck(this, this.name, nv); // No: can be initially Ambig - return reconstruct(name); - } - - @Override - public String toString() - { - //return this.data.toString(); - return this.name.toString(); - } - - @Override - //public PayloadType toPayloadType() // Currently can assume the only possible kind is DataTypeKind - //public PayloadType toPayloadType() // Currently can assume the only possible kind is DataTypeKind - public PayloadElemType toPayloadType() // Currently can assume the only possible kind is DataTypeKind - { - //return this.data.toPayloadType(); - return this.name.toPayloadType(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/context/DependencyMap.java b/scribble-core/src/main/java/org/scribble/ast/context/DependencyMap.java deleted file mode 100644 index 037a86027..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/context/DependencyMap.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Map.Entry; - -import org.scribble.type.name.ProtocolName; -import org.scribble.type.name.Role; - -import java.util.Set; - -// Mutable -// Used for two purposes: one to encapsulate Map structure and add method for ContextBuilder; second to allow overriding the generic types in ProtocolDeclContext (cf. nested Map generics) -public abstract class DependencyMap> // Maybe better to parameterise on Kind only? -{ - // self -> (proto -> target) -- the self role in this proto, depends on the proto, for the role param target - private final Map>> deps = new HashMap<>(); // All the potential dependencies from this protocol decl as the root - - public DependencyMap() - { - - } - - protected DependencyMap(DependencyMap deps) - { - for (Role r : deps.deps.keySet()) // FIXME: optimise - { - Map> tmp = deps.deps.get(r); - for (Entry> e : tmp.entrySet()) - { - for (Role rr : e.getValue()) - { - addProtocolDependency(r, e.getKey(), rr); - } - } - } - } - - public abstract DependencyMap clone(); - - public void addProtocolDependency(Role self, N pn, Role target) - { - Map> tmp1 = this.deps.get(self); - if (tmp1 == null) - { - tmp1 = new HashMap<>(); - this.deps.put(self, tmp1); - } - - Set tmp2 = tmp1.get(pn); - if (tmp2 == null) - { - tmp2 = new HashSet<>(); - tmp1.put(pn, tmp2); - } - tmp2.add(target); - } - - public Map>> getDependencies() - { - return this.deps; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/context/ModuleContext.java b/scribble-core/src/main/java/org/scribble/ast/context/ModuleContext.java deleted file mode 100644 index 2aed1551b..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/context/ModuleContext.java +++ /dev/null @@ -1,292 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context; - -import java.util.HashMap; -import java.util.Map; - -import org.scribble.ast.DataTypeDecl; -import org.scribble.ast.ImportDecl; -import org.scribble.ast.ImportModule; -import org.scribble.ast.MessageSigNameDecl; -import org.scribble.ast.Module; -import org.scribble.ast.NonProtocolDecl; -import org.scribble.ast.global.GProtocolDecl; -import org.scribble.ast.local.LProtocolDecl; -import org.scribble.main.JobContext; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.Global; -import org.scribble.type.kind.Kind; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.kind.SigKind; -import org.scribble.type.name.DataType; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.LProtocolName; -import org.scribble.type.name.MessageSigName; -import org.scribble.type.name.ModuleName; -import org.scribble.type.name.Name; -import org.scribble.type.name.ProtocolName; - -// Context information specific to each module as a root (wrt. to visitor passes) -public class ModuleContext -{ - public final ModuleName root; // full name - - // 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 = 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 final ScribNames visible = new ScribNames(); - - // Made by ModuleContextBuilder - // ModuleContext is the root context - public ModuleContext(JobContext jcontext, Module root) throws ScribbleException - { - ModuleName fullname = root.getFullModuleName(); - ModuleName simpname = root.moddecl.getDeclName(); - - this.root = fullname; - - // All transitive dependencies (for inlined and subprotocol visiting) - addModule(this.deps, root, fullname); - addImportDependencies(jcontext, root); - - // Names directly visible from this module - addModule(this.visible, root, fullname); - if (!fullname.equals(simpname)) - { - addModule(this.visible, root, simpname); - // Adds simple name of root as visible, and members qualified by simple name - } - addVisible(jcontext, root); - // Adds imports and members by their "direct" names (unqualified, except for no-alias imports) - } - - // 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 ScribbleException - { - names.modules.put(modname, mod.getFullModuleName()); - for (NonProtocolDecl npd : mod.getNonProtocolDecls()) - { - if (npd.isDataTypeDecl()) - { - DataTypeDecl dtd = (DataTypeDecl) npd; - DataType qualif = new DataType(modname, dtd.getDeclName()); - names.data.put(qualif, dtd.getFullMemberName(mod)); - } - else //if (npd.isMessageSigNameDecl()) - { - MessageSigNameDecl msnd = (MessageSigNameDecl) npd; - MessageSigName qualif = new MessageSigName(modname, msnd.getDeclName()); - names.sigs.put(qualif, msnd.getFullMemberName(mod)); - } - } - for (GProtocolDecl gpd : mod.getGlobalProtocolDecls()) - { - GProtocolName qualif = new GProtocolName(modname, gpd.getHeader().getDeclName()); - names.globals.put(qualif, gpd.getFullMemberName(mod)); - } - for (LProtocolDecl lpd : mod.getLocalProtocolDecls()) - { - LProtocolName qualif = new LProtocolName(modname, lpd.getHeader().getDeclName()); - names.locals.put(qualif, lpd.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(JobContext jcontext, Module mod) throws ScribbleException - { - for (ImportDecl id : mod.getImportDecls()) - { - if (id.isImportModule()) - { - ImportModule im = (ImportModule) id; - ModuleName fullmodname = im.modname.toName(); - if (!this.deps.modules.containsKey(fullmodname)) - { - Module imported = jcontext.getModule(fullmodname); - addModule(this.deps, imported, fullmodname); // Unlike for visible, only doing full names here - addImportDependencies(jcontext, imported); - } - } - else - { - throw new RuntimeException("TODO: " + id); - } - } - } - - // Adds "local" imports by alias or full name - // Adds "local" members by simple names - private void addVisible(JobContext jcontext, Module root) throws ScribbleException - { - // Unlike for deps, visible is not done transitively - for (ImportDecl id : root.getImportDecls()) - { - if (id.isImportModule()) - { - ImportModule im = (ImportModule) id; - ModuleName fullname = im.modname.toName(); - ModuleName visname = (im.isAliased()) ? im.getAlias() : fullname; // getVisibleName doesn't use fullname - if (this.visible.modules.containsKey(visname)) - { - throw new ScribbleException(id.getSource(), "Duplicate visible module name: " + visname); - } - Module imported = jcontext.getModule(fullname); - addModule(this.visible, imported, visname); - } - else - { - throw new RuntimeException("TODO: " + id); - } - } - - for (NonProtocolDecl npd : root.getNonProtocolDecls()) - { - if (npd.isDataTypeDecl()) - { - DataTypeDecl dtd = (DataTypeDecl) npd; - DataType visname = new DataType(dtd.getDeclName().toString()); - this.visible.data.put(visname, dtd.getFullMemberName(root)); - } - else //if (npd.isMessageSigNameDecl()) - { - MessageSigNameDecl msnd = (MessageSigNameDecl) npd; - MessageSigName visname = new MessageSigName(msnd.getDeclName().toString()); - this.visible.sigs.put(visname, msnd.getFullMemberName(root)); - } - } - for (GProtocolDecl gpd : root.getGlobalProtocolDecls()) - { - GProtocolName visname = new GProtocolName(gpd.getHeader().getDeclName().toString()); - this.visible.globals.put(visname, gpd.getFullMemberName(root)); - } - for (LProtocolDecl lpd : root.getLocalProtocolDecls()) - { - LProtocolName visname = new LProtocolName(lpd.getHeader().getDeclName().toString()); - this.visible.locals.put(visname, lpd.getFullMemberName(root)); - } - } - - /*public boolean isDataTypeDependency(DataType typename) - { - return this.deps.data.keySet().contains(typename); - } - - public boolean isMessageSigNameDependency(Name signame) - { - return this.deps.sigs.containsKey(signame); - }*/ - - // FIXME: 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 ProtocolName getProtocolDeclDependencyFullName(ProtocolName proto) - public ProtocolName checkProtocolDeclDependencyFullName(ProtocolName proto) - { - return getProtocolDeclFullName(this.deps, proto); - } - - public boolean isDataTypeVisible(DataType typename) - { - return this.visible.data.keySet().contains(typename); - } - - public boolean isMessageSigNameVisible(Name signame) - { - return this.visible.sigs.containsKey(signame); - } - - public DataType getVisibleDataTypeFullName(DataType visname) - { - return getFullName(this.visible.data, visname); - } - - public boolean isVisibleDataType(DataType visname) - { - return this.visible.isVisibleDataType(visname); - } - - public MessageSigName getVisibleMessageSigNameFullName(MessageSigName visname) - { - return getFullName(this.visible.sigs, visname); - } - - public ProtocolName getVisibleProtocolDeclFullName(ProtocolName visname) - { - return getProtocolDeclFullName(this.visible, visname); - } - - public boolean isVisibleProtocolDeclName(ProtocolName visname) - { - return this.visible.isVisibleProtocolDeclName(visname); - } - - public static ProtocolName getProtocolDeclFullName(ScribNames names, ProtocolName proto) - { - ProtocolName pn = (proto.getKind().equals(Global.KIND)) - ? getFullName(names.globals, (GProtocolName) proto) - : getFullName(names.locals, (LProtocolName) proto); - @SuppressWarnings("unchecked") - ProtocolName tmp = (ProtocolName) 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 + "]"; - } -} - -class ScribNames -{ - // names -> fully qualified names - protected final Map modules = new HashMap<>(); - protected final Map data = new HashMap<>(); - protected final Map sigs = new HashMap<>(); - protected final Map globals = new HashMap<>(); - protected 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(ProtocolName visname) - { - return this.globals.containsKey(visname) || this.locals.containsKey(visname); - } - - public boolean isVisibleDataType(DataType visname) - { - return this.data.containsKey(visname); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/context/ProtocolDeclContext.java b/scribble-core/src/main/java/org/scribble/ast/context/ProtocolDeclContext.java deleted file mode 100644 index 83a96e8b8..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/context/ProtocolDeclContext.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.ProtocolName; -import org.scribble.type.name.Role; - -public abstract class ProtocolDeclContext -{ - private Set roles; - - // cache of dependencies, cleared on entering each root global protocol - // protocol name is full name of global/local protocol dependencies - private DependencyMap> deps; - // All the potential protocol dependencies from this *protocoldecl* as the root -- cf. ModuleContext deps from Module root - - protected ProtocolDeclContext(Set roles, DependencyMap> deps) - { - this.roles = new HashSet<>(roles); - this.deps = deps.clone(); - } - - // Subclass constructor should use the above copy constructor - protected abstract ProtocolDeclContext copy(); - - public Set getRoleOccurrences() - { - return Collections.unmodifiableSet(this.roles); - } - - public ProtocolDeclContext setRoleOccurrences(Collection roles) - { - ProtocolDeclContext copy = copy(); - copy.roles = new HashSet<>(roles); - copy.deps = this.deps.clone(); - return copy; - } - - public DependencyMap> getDependencyMap() - { - // FIXME: returned deps view is mutable -- context should be immutable for del to be immutable - return this.deps; - } - - /*// Not needed: protocoldeclcontext always has dependencymap on first creation, by context building - public ProtocolDeclContext setDependencyMap(DependencyMap> deps) - { - ProtocolDeclContext copy = copy(); - copy.roles = new HashSet<>(this.roles); - copy.deps = new DependencyMap<>(deps); - return copy; - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/context/global/GDependencyMap.java b/scribble-core/src/main/java/org/scribble/ast/context/global/GDependencyMap.java deleted file mode 100644 index 4186e48be..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/context/global/GDependencyMap.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context.global; - -import org.scribble.ast.context.DependencyMap; -import org.scribble.type.name.GProtocolName; - -public class GDependencyMap extends DependencyMap -{ - protected GDependencyMap(GDependencyMap deps) - { - super(deps); - } - - public GDependencyMap() - { - super(); - } - - @Override - public GDependencyMap clone() - { - return new GDependencyMap(this); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/context/global/GProtocolDeclContext.java b/scribble-core/src/main/java/org/scribble/ast/context/global/GProtocolDeclContext.java deleted file mode 100644 index 58dbaa0e2..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/context/global/GProtocolDeclContext.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context.global; - -import java.util.Collections; -import java.util.Set; - -import org.scribble.ast.context.ProtocolDeclContext; -import org.scribble.type.kind.Global; -import org.scribble.type.name.Role; - -public class GProtocolDeclContext extends ProtocolDeclContext -{ - protected GProtocolDeclContext(Set roles, GDependencyMap deps) - { - super(roles, deps); - } - - public GProtocolDeclContext(GDependencyMap deps) - { - this(Collections.emptySet(), deps); - } - - @Override - protected GProtocolDeclContext copy() - { - return new GProtocolDeclContext(getRoleOccurrences(), getDependencyMap()); - } - - @Override - public GDependencyMap getDependencyMap() - { - return (GDependencyMap) super.getDependencyMap(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/context/local/LDependencyMap.java b/scribble-core/src/main/java/org/scribble/ast/context/local/LDependencyMap.java deleted file mode 100644 index 9d9540aef..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/context/local/LDependencyMap.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context.local; - -import org.scribble.ast.context.DependencyMap; -import org.scribble.type.name.LProtocolName; - -public class LDependencyMap extends DependencyMap -{ - protected LDependencyMap(LDependencyMap deps) - { - super(deps); - } - - public LDependencyMap() - { - super(); - } - - @Override - public LDependencyMap clone() - { - return new LDependencyMap(this); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/context/local/LProjectionDeclContext.java b/scribble-core/src/main/java/org/scribble/ast/context/local/LProjectionDeclContext.java deleted file mode 100644 index 758fce715..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/context/local/LProjectionDeclContext.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context.local; - -import java.util.Set; - -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.Role; - - -@Deprecated -public class LProjectionDeclContext extends LProtocolDeclContext -{ - private GProtocolName fullname; - private Role self; - - protected LProjectionDeclContext(Set roles, LDependencyMap deps, GProtocolName gpn, Role self) - { - super(roles, deps); - } - - @Override - public LProjectionDeclContext copy() - { - return new LProjectionDeclContext(getRoleOccurrences(), getDependencyMap(), getSourceProtocol(), getSelfRole()); - } - - public GProtocolName getSourceProtocol() - { - return this.fullname; - } - - // Redundant with SelfRoleDecl in header - public Role getSelfRole() - { - return this.self; - } -} - diff --git a/scribble-core/src/main/java/org/scribble/ast/context/local/LProtocolDeclContext.java b/scribble-core/src/main/java/org/scribble/ast/context/local/LProtocolDeclContext.java deleted file mode 100644 index f96fff131..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/context/local/LProtocolDeclContext.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context.local; - -import java.util.Collections; -import java.util.Set; - -import org.scribble.ast.context.ProtocolDeclContext; -import org.scribble.type.kind.Local; -import org.scribble.type.name.Role; - -public class LProtocolDeclContext extends ProtocolDeclContext -{ - protected LProtocolDeclContext(Set roles, LDependencyMap deps) - { - super(roles, deps); - } - - public LProtocolDeclContext(LDependencyMap deps) - { - this(Collections.emptySet(), deps); - } - - @Override - protected LProtocolDeclContext copy() - { - return new LProtocolDeclContext(getRoleOccurrences(), getDependencyMap()); - } - - @Override - public LDependencyMap getDependencyMap() - { - return (LDependencyMap) super.getDependencyMap(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GChoice.java b/scribble-core/src/main/java/org/scribble/ast/global/GChoice.java deleted file mode 100644 index 5718f822d..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GChoice.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Choice; -import org.scribble.ast.ProtocolBlock; -import org.scribble.ast.ScribNodeBase; -import org.scribble.ast.local.LChoice; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ScribDel; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.Global; -import org.scribble.type.name.Role; -import org.scribble.util.ScribUtil; - -public class GChoice extends Choice implements GCompoundInteractionNode -{ - public GChoice(CommonTree source, RoleNode subj, List blocks) - { - super(source, subj, blocks); - } - - // Similar pattern to reconstruct - // Idea is, if extending the AST class (more fields), then reconstruct/project should also be extended (and called from extended del) - public LChoice project(AstFactory af, Role self, List blocks) - { - LChoice projection = null; // Individual GlobalInteractionNodes become null if not projected -- projected seqs and blocks are never null though - /*if (blocks.size() == 1) - { - if (!blocks.get(0).isEmpty()) // WF allows empty (blocks/seq are never null) - { - RoleNode subj = AstFactoryImpl.FACTORY.DummyProjectionRoleNode(); - projection = AstFactoryImpl.FACTORY.LChoice(subj, blocks); - } - } - else //if (blocks.size() > 1)*/ - blocks = blocks.stream().filter((b) -> !b.isEmpty()).collect(Collectors.toList()); - if (!blocks.isEmpty()) - { - // FIXME? initially keep global subject, and later overwrite as necessary in projections? (algorithm currently checks for DUMMY) - RoleNode subj = self.equals(this.subj.toName()) ? this.subj.clone(af) : af.DummyProjectionRoleNode(); - List cs = blocks.stream().map(b -> af.LChoice(this.source, subj, Arrays.asList(b))).collect(Collectors.toList()); - // Hacky: keeping this.source for each LChoice (will end up as the source for the final merged LChoice) - LChoice merged = cs.get(0); - try - { - for (int i = 1; i < cs.size(); i++) - { - merged = merged.merge(af, cs.get(i)); // Merge currently does "nothing"; validation takes direct non-deterministic interpretation -- purpose of syntactic merge is to convert non-det to "equivalent" safe det in certain sitations - } - } - catch (ScribbleException e) // HACK - { - throw new RuntimeScribbleException(e); - } - projection = merged; - } - - return projection; - } - - @Override - protected ScribNodeBase copy() - { - return new GChoice(this.source, this.subj, getBlocks()); - } - - @Override - public GChoice clone(AstFactory af) - { - RoleNode subj = this.subj.clone(af); - List blocks = ScribUtil.cloneList(af, getBlocks()); - return af.GChoice(this.source, subj, blocks); - } - - @Override - public GChoice reconstruct(RoleNode subj, List> blocks) - { - ScribDel del = del(); - GChoice gc = new GChoice(this.source, subj, castBlocks(blocks)); - gc = (GChoice) gc.del(del); - return gc; - } - - @Override - public List getBlocks() - { - return castBlocks(super.getBlocks()); - } - - private static List castBlocks(List> blocks) - { - return blocks.stream().map((b) -> (GProtocolBlock) b).collect(Collectors.toList()); - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Global getKind() - { - return GCompoundInteractionNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GCompoundInteractionNode.java b/scribble-core/src/main/java/org/scribble/ast/global/GCompoundInteractionNode.java deleted file mode 100644 index 9eb86d367..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GCompoundInteractionNode.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 GCompoundInteractionNode extends GInteractionNode -{ - -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GConnect.java b/scribble-core/src/main/java/org/scribble/ast/global/GConnect.java deleted file mode 100644 index 76d071700..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GConnect.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.ConnectionAction; -import org.scribble.ast.Constants; -import org.scribble.ast.MessageNode; -import org.scribble.ast.local.LNode; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.Global; -import org.scribble.type.kind.RoleKind; -import org.scribble.type.name.Role; - -public class GConnect extends ConnectionAction implements GSimpleInteractionNode -{ - public GConnect(CommonTree source, RoleNode src, MessageNode msg, RoleNode dest) - //public GConnect(RoleNode src, RoleNode dest) - { - super(source, src, msg, dest); - //super(src, dest); - } - - public LNode project(AstFactory af, Role self) - { - Role srcrole = this.src.toName(); - Role destrole = this.dest.toName(); - LNode projection = null; - if (srcrole.equals(self) || destrole.equals(self)) - { - if (srcrole.equals(destrole)) - { - throw new RuntimeException("Shouldn't get in here (self-connection): " + this); - } - - RoleNode src = (RoleNode) af.SimpleNameNode(this.src.getSource(), RoleKind.KIND, this.src.toName().toString()); // clone? - MessageNode msg = (MessageNode) this.msg; // FIXME: need namespace prefix update? - RoleNode dest = (RoleNode) af.SimpleNameNode(this.dest.getSource(), RoleKind.KIND, this.dest.toName().toString()); - if (srcrole.equals(self)) - { - projection = af.LConnect(this.source, src, msg, dest); - //projection = AstFactoryImpl.FACTORY.LConnect(src, dest); // src and dest (not self and peer) - } - if (destrole.equals(self)) - { - projection = af.LAccept(this.source, src, msg, dest); - //projection = AstFactoryImpl.FACTORY.LAccept(src, dest); - } - } - return projection; - } - - @Override - protected GConnect copy() - { - return new GConnect(this.source, this.src, this.msg, this.dest); - //return new GConnect(this.src, this.dest); - } - - @Override - public GConnect clone(AstFactory af) - { - RoleNode src = this.src.clone(af); - MessageNode msg = this.msg.clone(af); - RoleNode dest = this.dest.clone(af); - return af.GConnect(this.source, src, msg, dest); - //return AstFactoryImpl.FACTORY.GConnect(src, dest); - } - - @Override - public GConnect reconstruct(RoleNode src, MessageNode msg, RoleNode dest) - //public GConnect reconstruct(RoleNode src, RoleNode dest) - { - ScribDel del = del(); - GConnect gc = new GConnect(this.source, src, msg, dest); - //GConnect gc = new GConnect(src, dest); - gc = (GConnect) gc.del(del); - return gc; - } - - @Override - public String toString() - { - return (isUnitMessage() ? "" : this.msg + " ") + Constants.CONNECT_KW + " " + this.src + " " + Constants.TO_KW + " " + this.dest + ";"; - //return Constants.CONNECT_KW + " " + this.src + " " + Constants.TO_KW + " " + this.dest + ";"; - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Global getKind() - { - return GSimpleInteractionNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GContinue.java b/scribble-core/src/main/java/org/scribble/ast/global/GContinue.java deleted file mode 100644 index e694ba55f..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GContinue.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Continue; -import org.scribble.ast.local.LContinue; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.Global; -import org.scribble.type.kind.RecVarKind; -import org.scribble.type.name.Role; - -public class GContinue extends Continue implements GSimpleInteractionNode -{ - public GContinue(CommonTree source, RecVarNode recvar) - { - super(source, recvar); - } - - public LContinue project(AstFactory af, Role self) - { - RecVarNode recvar = (RecVarNode) af.SimpleNameNode(this.recvar.getSource(), RecVarKind.KIND, this.recvar.toName().toString()); // clone? - LContinue projection = af.LContinue(this.source, recvar); - return projection; - } - - @Override - protected GContinue copy() - { - return new GContinue(this.source, this.recvar); - } - - @Override - public GContinue clone(AstFactory af) - { - RecVarNode rv = this.recvar.clone(af); - return af.GContinue(this.source, rv); - } - - @Override - public GContinue reconstruct(RecVarNode recvar) - { - ScribDel del = del(); - GContinue gc = new GContinue(this.source, recvar); - gc = (GContinue) gc.del(del); - return gc; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GDelegationElem.java b/scribble-core/src/main/java/org/scribble/ast/global/GDelegationElem.java deleted file mode 100644 index f8e33532d..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GDelegationElem.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.PayloadElem; -import org.scribble.ast.ScribNodeBase; -import org.scribble.ast.local.LDelegationElem; -import org.scribble.ast.name.qualified.GProtocolNameNode; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ScribDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.Local; -import org.scribble.type.name.GDelegationType; -import org.scribble.type.name.PayloadElemType; -import org.scribble.visit.AstVisitor; -import org.scribble.visit.context.Projector; - -// 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 GDelegationElem extends ScribNodeBase implements PayloadElem -{ - // Currently no potential for ambiguity, cf. UnaryPayloadElem (DataTypeNameNode or ParameterNode) - public final GProtocolNameNode proto; // Becomes full name after disambiguation - public final RoleNode role; - - public GDelegationElem(CommonTree source, GProtocolNameNode proto, RoleNode role) - { - //super(proto); - super(source); - this.proto = proto; - this.role = role; - } - - @Override - public LDelegationElem project(AstFactory af) - { - return af.LDelegationElem(this.source, Projector.makeProjectedFullNameNode(af, this.source, this.proto.toName(), this.role.toName())); - } - - @Override - public boolean isGlobalDelegationElem() - { - return true; - } - - @Override - protected GDelegationElem copy() - { - return new GDelegationElem(this.source, this.proto, this.role); - } - - @Override - public GDelegationElem clone(AstFactory af) - { - GProtocolNameNode name = (GProtocolNameNode) this.proto.clone(af); - RoleNode role = (RoleNode) this.role.clone(af); - return af.GDelegationElem(this.source, name, role); - } - - public GDelegationElem reconstruct(GProtocolNameNode proto, RoleNode role) - { - ScribDel del = del(); - GDelegationElem elem = new GDelegationElem(this.source, proto, role); - elem = (GDelegationElem) elem.del(del); - return elem; - } - - @Override - public GDelegationElem visitChildren(AstVisitor nv) throws ScribbleException - { - GProtocolNameNode name = (GProtocolNameNode) visitChild(this.proto, nv); - RoleNode role = (RoleNode) visitChild(this.role, nv); - return reconstruct(name, role); - } - - @Override - public String toString() - { - return this.proto + "@" + this.role; - } - - @Override - public PayloadElemType toPayloadType() - { - return new GDelegationType(this.proto.toName(), this.role.toName()); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GDisconnect.java b/scribble-core/src/main/java/org/scribble/ast/global/GDisconnect.java deleted file mode 100644 index 315103fd1..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GDisconnect.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.ConnectionAction; -import org.scribble.ast.Constants; -import org.scribble.ast.MessageNode; -import org.scribble.ast.MessageSigNode; -import org.scribble.ast.local.LNode; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.Global; -import org.scribble.type.kind.RoleKind; -import org.scribble.type.name.Role; - -public class GDisconnect extends ConnectionAction implements GSimpleInteractionNode -{ - - //public GDisconnect(CommonTree source, RoleNode src, RoleNode dest) - public GDisconnect(CommonTree source, MessageSigNode unit, RoleNode src, RoleNode dest) - { - super(source, src, unit, dest); - } - - public LNode project(AstFactory af, Role self) - { - Role srcrole = this.src.toName(); - Role destrole = this.dest.toName(); - LNode projection = null; - if (srcrole.equals(self) || destrole.equals(self)) - { - RoleNode src = (RoleNode) af.SimpleNameNode(this.src.getSource(), RoleKind.KIND, this.src.toName().toString()); // clone? - RoleNode dest = (RoleNode) af.SimpleNameNode(this.dest.getSource(), RoleKind.KIND, this.dest.toName().toString()); - if (srcrole.equals(self)) - { - projection = af.LDisconnect(this.source, src, dest); - } - if (destrole.equals(self)) - { - projection = af.LDisconnect(this.source, dest, src); - } - } - return projection; - } - - - @Override - protected GDisconnect copy() - { - return new GDisconnect(this.source, (MessageSigNode) this.msg, this.src, this.dest); - } - - @Override - public GDisconnect clone(AstFactory af) - { - RoleNode src = this.src.clone(af); - RoleNode dest = this.dest.clone(af); - return af.GDisconnect(this.source, src, dest); - } - - @Override - public GDisconnect reconstruct(RoleNode src, MessageNode msg, RoleNode dest) - //public GDisconnect reconstruct(RoleNode src, RoleNode dest) - { - ScribDel del = del(); - GDisconnect gd = new GDisconnect(this.source, (MessageSigNode) this.msg, src, dest); - gd = (GDisconnect) gd.del(del); - return gd; - } - - @Override - public String toString() - { - return Constants.DISCONNECT_KW + " " + this.src + " " + Constants.TO_KW + " " + this.dest + ";"; - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Global getKind() - { - return GSimpleInteractionNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GDo.java b/scribble-core/src/main/java/org/scribble/ast/global/GDo.java deleted file mode 100644 index 2197d7bb7..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GDo.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Do; -import org.scribble.ast.NonRoleArgList; -import org.scribble.ast.RoleArgList; -import org.scribble.ast.ScribNodeBase; -import org.scribble.ast.context.ModuleContext; -import org.scribble.ast.local.LDo; -import org.scribble.ast.name.qualified.GProtocolNameNode; -import org.scribble.ast.name.qualified.LProtocolNameNode; -import org.scribble.ast.name.qualified.ProtocolNameNode; -import org.scribble.del.ScribDel; -import org.scribble.main.JobContext; -import org.scribble.type.kind.Global; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.Role; - -public class GDo extends Do implements GSimpleInteractionNode -{ - public GDo(CommonTree source, RoleArgList roles, NonRoleArgList args, GProtocolNameNode proto) - { - super(source, roles, args, proto); - } - - public LDo project(AstFactory af, Role self, LProtocolNameNode fullname) - { - RoleArgList roleinstans = this.roles.project(af, self); - NonRoleArgList arginstans = this.args.project(af, self); - LDo projection = af.LDo(this.source, roleinstans, arginstans, fullname); - return projection; - } - - @Override - protected ScribNodeBase copy() - { - return new GDo(this.source, this.roles, this.args, getProtocolNameNode()); - } - - @Override - public GDo clone(AstFactory af) - { - RoleArgList roles = this.roles.clone(af); - NonRoleArgList args = this.args.clone(af); - GProtocolNameNode proto = this.getProtocolNameNode().clone(af); - return af.GDo(this.source, roles, args, proto); - } - - @Override - public GDo reconstruct(RoleArgList roles, NonRoleArgList args, ProtocolNameNode proto) - { - ScribDel del = del(); - GDo gd = new GDo(this.source, roles, args, (GProtocolNameNode) proto); - gd = (GDo) gd.del(del); - return gd; - } - - @Override - public GProtocolNameNode getProtocolNameNode() - { - return (GProtocolNameNode) this.proto; - } - - @Override - public GProtocolName getTargetProtocolDeclFullName(ModuleContext mcontext) - { - return (GProtocolName) super.getTargetProtocolDeclFullName(mcontext); - } - - @Override - public GProtocolDecl getTargetProtocolDecl(JobContext jcontext, ModuleContext mcontext) - { - return (GProtocolDecl) super.getTargetProtocolDecl(jcontext, mcontext); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GInteractionNode.java b/scribble-core/src/main/java/org/scribble/ast/global/GInteractionNode.java deleted file mode 100644 index e38f4a4a3..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GInteractionNode.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.InteractionNode; -import org.scribble.type.kind.Global; - -// Alternatively to interface, use GlobalNode subclass with delegation to "super" base (e.g. Choice) classes -public interface GInteractionNode extends InteractionNode, GNode -{ - -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GInteractionSeq.java b/scribble-core/src/main/java/org/scribble/ast/global/GInteractionSeq.java deleted file mode 100644 index 85f375026..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GInteractionSeq.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.InteractionNode; -import org.scribble.ast.InteractionSeq; -import org.scribble.ast.local.LInteractionNode; -import org.scribble.ast.local.LInteractionSeq; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.Global; -import org.scribble.type.name.Role; -import org.scribble.util.ScribUtil; - -public class GInteractionSeq extends InteractionSeq implements GNode -{ - public GInteractionSeq(CommonTree source, List actions) - { - super(source, actions); - } - - // Move node-specific projects to G nodes (not dels) and take child projections as params, bit like reconstruct - public LInteractionSeq project(AstFactory af, Role self, List lis) - { - LInteractionSeq projection = af.LInteractionSeq(this.source, lis); - return projection; - } - - @Override - protected GInteractionSeq copy() - { - return new GInteractionSeq(this.source, getInteractions()); - } - - @Override - public GInteractionSeq clone(AstFactory af) - { - List gis = ScribUtil.cloneList(af, getInteractions()); - return af.GInteractionSeq(this.source, gis); - } - - @Override - public GInteractionSeq reconstruct(List> ins) - { - ScribDel del = del(); - GInteractionSeq gis = new GInteractionSeq(this.source, castNodes(ins)); - gis = (GInteractionSeq) gis.del(del); - return gis; - } - - @Override - public List getInteractions() - { - return castNodes(super.getInteractions()); - } - - private static List castNodes(List> nodes) - { - return nodes.stream().map((n) -> (GInteractionNode) n).collect(Collectors.toList()); - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Global getKind() - { - return GNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GInterrupt.java b/scribble-core/src/main/java/org/scribble/ast/global/GInterrupt.java deleted file mode 100644 index b49fe6689..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GInterrupt.java +++ /dev/null @@ -1,199 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.Interrupt; -import org.scribble.ast.MessageNode; -import org.scribble.ast.name.simple.RoleNode; - -public class GInterrupt extends Interrupt implements GSimpleInteractionNode -{ - /*public static final Function toGlobalInterrupt = - (Interrupt interr) -> (GlobalInterrupt) interr;*/ - - public GInterrupt(CommonTree source, RoleNode src, List msgs) - { - //this(ct, src, msgs, null, null); - //this(t, src, msgs, null, null); - super(source, src, msgs); - } - - /*// Destination Roles is "type info", not a syntax element -- could wrap in a generic "type info" object - //public GlobalInterrupt(CommonTree ct, RoleNode src, List msgs)//, List dests) - public GlobalInterrupt(CommonTree ct, RoleNode src, List msgs, GlobalInterruptContext icontext) - { - //super(ct, src, msgs);//, dests); - super(ct, src, msgs, icontext); - }*/ - - /*protected GlobalInterrupt(CommonTree ct, RoleNode src, List msgs, GlobalInterruptContext icontext, Env env) - { - //super(ct, src, msgs);//, dests); - super(ct, src, msgs, icontext, env); - } - - //@Override // LocalInterrupt has a different signature - protected GlobalInterrupt reconstruct(CommonTree ct, RoleNode src, List msgs, GlobalInterruptContext icontext, Env env) - { - return new GlobalInterrupt(ct, src, msgs, icontext, env); - } - - @Override - public GlobalInterrupt leaveWFChoiceCheck(WellFormedChoiceChecker checker) throws ScribbleException - { - Role src = this.src.toName(); - if (!checker.getEnv().isEnabled(src)) - { - throw new ScribbleException("Role not enabled: " + src); - } - return (GlobalInterrupt) super.leaveWFChoiceCheck(checker); - /*Interrupt interr = super.leaveWFChoiceCheck(checker); - return new GlobalInterrupt(interr.ct, interr.src, interr.msgs, interr.getContext(), interr.getEnv());* / - } - - @Override - public GlobalInterrupt leaveProjection(Projector proj) //throws ScribbleException - { - Role self = proj.peekSelf(); - Role srcrole = this.src.toName(); - List destroles = ((GlobalInterruptContext) getContext()).getDestinations(); - LocalInterrupt projection = null; - if (srcrole.equals(self) || destroles.contains(self)) - { - RoleNode src = new RoleNode(null, this.src.toName().toString()); // FIXME: project by visiting - List msgs = - this.msgs.stream().map((m) -> (MessageNode) ((ProjectionEnv) m.getEnv()).getProjection()).collect(Collectors.toList()); - List dests = - destroles.stream().map((d) -> new RoleNode(null, d.toString())).collect(Collectors.toList()); - if (srcrole.equals(self)) - { - projection = new LocalThrows(null, src, msgs, dests); - } - else if (destroles.contains(self)) - { - projection = new LocalCatches(null, src, msgs, dests); - } - } - this.setEnv(new ProjectionEnv(proj.getJobContext(), proj.getModuleContext(), projection)); - return this; - } - - /*@Override - public GlobalInterrupt leaveContextBuilding(Node parent, NodeContextBuilder builder) throws ScribbleException - { - GlobalInterrupt interr = (GlobalInterrupt) super.leaveContextBuilding(parent, builder); - ProtocolBlockContext bcontext = (ProtocolBlockContext) ((GlobalInterruptible) parent).block.getContext(); - - System.out.println("3: " + bcontext); - - List dests = new LinkedList<>(bcontext.getRoles()); - // FIXME: also include other interrupt sources? (would be better to do in GlobalInterruptible) - dests.remove(this.src.toName()); - return new GlobalInterrupt(interr.ct, interr.src, interr.msgs, dests); - }*/ - - /*@Override - public GlobalInterrupt substitute(Substitutor subs) throws ScribbleException - { - Interrupt interr = super.substitute(subs); - return new GlobalInterrupt(interr.ct, interr.src, interr.msgs, interr.dests); - } - - @Override - public GlobalInterrupt checkWellFormedness(WellFormednessChecker wfc) throws ScribbleException - { - GlobalInterrupt gi = (GlobalInterrupt) super.checkWellFormedness(wfc); - Env env = wfc.getEnv(); - Role src = this.src.toName(); - if (!env.roles.isRoleEnabled(src)) - { - throw new ScribbleException("Interrupt role not enabled: " + src); - } - for (MessageNode msg : this.msgs) - { - // Duplicated from GlobalMesssageTransfer - if (msg.isParameterNode()) - { - //MessageSignatureParameter param = ((ParameterNode) msg).toMessageSignatureParameter(); - Parameter param = ((ParameterNode) msg).toName(); - if (!env.params.isParameterDeclared(param)) - { - throw new ScribbleException("Bad parameter: " + param); - } - ParameterDecl.Kind pdkind = env.params.getParameterKind(((ParameterNode) msg).toName()); - if (!pdkind.equals(ParameterDecl.Kind.SIG)) - { - throw new ScribbleException("GlobalMessageTransfer type parameter should be of SIG kind, not: " + pdkind); - } - } - } - Set dests = new HashSet<>(); - dests.addAll(env.ops.getSources()); - dests.addAll(env.ops.getAllDestinations()); - dests.remove(this.src.toName()); - return new GlobalInterrupt(gi.ct, gi.src, gi.msgs, new LinkedList<>(dests)); - } - - @Override - public LocalNode project(Projector proj) - { - Role role = proj.getRole(); - if (this.src.toName().equals(role)) - { - return new LocalThrows(null, this.src, this.msgs, this.dests); - } - else if (this.dests.contains(role)) - { - return new LocalCatches(null, this.src, this.msgs, this.dests); - } - return null; - } - - @Override - public GlobalInterrupt collectRoles(RoleCollector rc) throws ScribbleException - { - rc.addRole(this.src.toName()); - for (Role dest : this.dests) - { - rc.addRole(dest); - } - return (GlobalInterrupt) super.collectRoles(rc); - }* / - - @Override - public GlobalInterrupt visitChildren(NodeVisitor nv) throws ScribbleException - { - Interrupt interr = super.visitChildren(nv); - //return new GlobalInterrupt(interr.ct, interr.src, interr.msgs); //, interr.dests); - //return new GlobalInterrupt(interr.ct, interr.src, interr.msgs, interr.getContext(), interr.getEnv()); - return reconstruct(interr.ct, interr.src, interr.msgs, interr.getContext(), interr.getEnv()); - }*/ - - /*@Override - public String toString() - { - return this.getMessages().stream().map((msg) -> msg.toString()).collect(Collectors.joining(", ")) - + " " + Constants.BY_KW + " " + this.src + ";"; - }*/ - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Global getKind() - { - return GSimpleInteractionNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GInterruptible.java b/scribble-core/src/main/java/org/scribble/ast/global/GInterruptible.java deleted file mode 100644 index 734cf5017..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GInterruptible.java +++ /dev/null @@ -1,282 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Interruptible; -import org.scribble.ast.ProtocolBlock; -import org.scribble.ast.ScribNodeBase; -import org.scribble.ast.name.simple.ScopeNode; -import org.scribble.type.kind.Global; -import org.scribble.type.kind.ScopeKind; -import org.scribble.type.name.Name; - -//public class GlobalInterruptible extends Interruptible implements GlobalInteractionNode -public class GInterruptible extends Interruptible implements GCompoundInteractionNode -{ - /*public static final Function toGlobalInterrupt = - (Interrupt interr) - -> (GlobalInterrupt) interr; - - public static final Function, List> toGlobalInterruptList = - (List interrs) - -> interrs.stream().map(GlobalInterruptible.toGlobalInterrupt).collect(Collectors.toList());*/ - - //public GlobalInterruptible(GlobalProtocolBlock block, List interrs) - public GInterruptible(CommonTree source, ProtocolBlock block, List interrs) - { - //this(null, block, interrs, null, null); - this(source, null, block, interrs); - } - - //public GlobalInterruptible(ScopeNode scope, GlobalProtocolBlock block, List interrs) - public GInterruptible(CommonTree source, ScopeNode scope, ProtocolBlock block, List interrs) - { - //this(ct, scope, block, interrs, null, null); - super(source, scope, block, interrs); - } - - @Override - protected ScribNodeBase copy() - { - throw new RuntimeException("TODO: " + this); - } - - @Override - public GInterruptible clone(AstFactory af) - { - throw new RuntimeException("TODO: " + this); - } - - @Override - public boolean isEmptyScope() - { - throw new RuntimeException("TODO: " + this); - } - - @Override - public Name getScopeElement() - { - throw new RuntimeException("TODO: " + this); - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Global getKind() - { - return GCompoundInteractionNode.super.getKind(); - }*/ - - - - - - /*protected GlobalInterruptible(CommonTree ct, ScopeNode scope, GlobalProtocolBlock block, List interrs, CompoundInteractionNodeContext icontext) - { - super(ct, scope, block, interrs, icontext); - }* / - - protected GlobalInterruptible(CommonTree ct, ScopeNode scope, GlobalProtocolBlock block, List interrs, CompoundInteractionNodeContext icontext, Env env) - { - super(ct, scope, block, interrs, icontext, env); - } - - @Override - protected GlobalInterruptible reconstruct(CommonTree ct, ScopeNode scope, GlobalProtocolBlock block, List interrs, CompoundInteractionNodeContext icontext, Env env) - { - return new GlobalInterruptible(ct, scope, block, interrs, icontext, env); - } - - @Override - public GlobalInterruptible leaveDisambiguation(NameDisambiguator disamb) throws ScribbleException - { - ScopeNode scope = this.scope; - if (scope == null) - { - scope = disamb.getFreshScope(); - } - //return new GlobalInterruptible(this.ct, scope, this.block, this.interrs); - return reconstruct(this.ct, scope, this.block, this.interrs, getContext(), getEnv()); - } - - @Override - public GlobalInterruptible leaveContextBuilding(NodeContextBuilder builder) throws ScribbleException - { - Interruptible intt = super.leaveContextBuilding(builder); - ProtocolBlockContext bcontext = intt.block.getContext(); - // Interrupt dests building done here (in the parent) because visitor pattern for context building doesn't easily allow children (block and interrupts) to see each other's contexts - List interrs = new LinkedList(); - //ProtocolDeclContext pdcontext = builder.getProtocolDeclContext(); - for (GlobalInterrupt interr : intt.interrs) - { - Role src = interr.src.toName(); - List dests = new LinkedList<>(bcontext.getRoles()); - // FIXME: also include other interrupt sources? - dests.remove(src); - GlobalInterruptContext icontext = new GlobalInterruptContext(dests); - interrs.add(new GlobalInterrupt(interr.ct, interr.src, interr.msgs, icontext, interr.getEnv())); - CompoundInteractionContext cicontext = (CompoundInteractionContext) builder.peekContext(); - for (Role dest : dests) // Cannot do in super Interruptible because dest info not available yet - { - for (MessageNode mn : interr.msgs) - { - Message msg = mn.toMessage(); - //((CompoundInteractionContext) builder.peekContext()).addInterrupt(src, dest, msg); - //builder.replaceContext(((CompoundInteractionContext) builder.peekContext()).addInterrupt(src, dest, msg)); - cicontext = cicontext.addInterrupt(src, dest, msg); - } - } - builder.replaceContext(cicontext); - } - //return new GlobalInterruptible(intt.ct, intt.scope, intt.block, interrs, intt.getContext()); - return reconstruct(intt.ct, intt.scope, intt.block, interrs, intt.getContext(), getEnv()); - } - - @Override - public GlobalInterruptible leaveProjection(Projector proj) //throws ScribbleException - { - ScopeNode scope = new ScopeNode(null, this.scope.toName().toString()); // Inconsistent to copy role nodes manually, but do via children visiting for other children - LocalProtocolBlock block = (LocalProtocolBlock) ((ProjectionEnv) this.block.getEnv()).getProjection(); - /*List interrs = - this.interrs.stream().map(() -> (LocalInterrupt) ((ProjectionEnv) .getEnv()).getProjection()).collect(Collectors.toList());* / - LocalThrows thro = null; - List cats = new LinkedList<>(); - for (GlobalInterrupt gi : this.interrs) - { - LocalInterrupt li = (LocalInterrupt) ((ProjectionEnv) gi.getEnv()).getProjection(); - if (li != null) - { - if (li instanceof LocalThrows) - { - thro = (LocalThrows) li; - } - else - { - cats.add((LocalCatches) li); - } - } - } - LocalInterruptible projection = null; - if (!block.isEmpty() || thro != null) - { - projection = new LocalInterruptible(ct, scope, block, thro, cats); - } - this.setEnv(new ProjectionEnv(proj.getJobContext(), proj.getModuleContext(), projection)); - return this; - } - - /*@Override - public GlobalInterruptible leaveWFChoiceCheck(WellFormedChoiceChecker checker) throws ScribbleException - { - Interruptible intt = super.leaveWFChoiceCheck(checker); - return new GlobalInterruptible(intt.ct, intt.scope, intt.block, intt.interrs, intt.getContext(), intt.getEnv()); - }*/ - - /*@Override - public Env enter(EnvVisitor nv) throws ScribbleException - { - Env env = nv.getEnv(); - if (nv instanceof WellFormednessChecker) // Hacky - { - Scope scope = this.scope.toName(); - if (env.scopes.getScopes().contains(scope)) - { - throw new ScribbleException("Duplicate scope: " + scope); - } - } - return super.enter(nv); - } - - @Override - public GlobalInterruptible checkWellFormedness(WellFormednessChecker wfc) throws ScribbleException - { - GlobalInterruptible gi = (GlobalInterruptible) super.checkWellFormedness(wfc); // visitChildren - Env env = gi.block.getEnv(); - Set roles = new HashSet<>(); - for (Interrupt interr : gi.interrs) - { - //GlobalInterrupt interr = (GlobalInterrupt) foo; - Role src = interr.src.toName(); - if (roles.contains(src)) - { - throw new ScribbleException("Duplicate interrupt source role: " + src); - } - roles.add(src); - if (env.ops.getSources().contains(src)) - { - Set ops = new HashSet<>(env.ops.getAll(src)); - List tmp = interr.getOperators(env); - ops.retainAll(tmp); - if (!ops.isEmpty()) - { - throw new ScribbleException("Bad interrupt operators: " + tmp); - } - } - } - return gi; - } - - @Override - public LocalInterruptible project(Projector proj) throws ScribbleException - { - // Not calling super method (doing child visiting manually) - LocalProtocolBlock block = (LocalProtocolBlock) proj.visit(this.block); - LocalThrows thro = null; - List cats = new LinkedList<>(); - for (Interrupt interr : this.interrs) - { - if (!interr.dests.isEmpty()) // HACK: make more proper -- if no one to throw interr to, cannot throw (so don't project) - { - LocalNode ln = (LocalNode) proj.visit(interr); - if (ln != null) - { - if (block == null) - { - LocalInteractionSequence lis = new LocalInteractionSequence(null, Collections.emptyList()); - block = new LocalProtocolBlock(null, lis); - } - - if (ln instanceof LocalThrows) - { - if (thro != null) - { - throw new RuntimeException("Shouldn't get in here: " + this); - } - thro = (LocalThrows) ln; - } - else - { - cats.add((LocalCatches) ln); - } - } - } - } - if (block == null && thro == null && cats.isEmpty()) - { - return null; - } - return new LocalInterruptible(null, this.scope, block, thro, cats); - }*/ - - /*@Override - public GlobalInterruptible visitChildren(NodeVisitor nv) throws ScribbleException - { - Interruptible intt = super.visitChildren(nv); - //List interrs = GlobalInterruptible.toGlobalInterruptList.apply(intt.interrs); - return new GlobalInterruptible(intt.ct, intt.scope, intt.block, intt.interrs, intt.getContext(), intt.getEnv()); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GMessageTransfer.java b/scribble-core/src/main/java/org/scribble/ast/global/GMessageTransfer.java deleted file mode 100644 index 944f8cedc..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GMessageTransfer.java +++ /dev/null @@ -1,113 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Constants; -import org.scribble.ast.MessageNode; -import org.scribble.ast.MessageTransfer; -import org.scribble.ast.local.LInteractionNode; -import org.scribble.ast.local.LNode; -import org.scribble.ast.local.LReceive; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.Global; -import org.scribble.type.kind.RoleKind; -import org.scribble.type.name.Role; -import org.scribble.util.ScribUtil; - -public class GMessageTransfer extends MessageTransfer implements GSimpleInteractionNode -{ - public GMessageTransfer(CommonTree source, RoleNode src, MessageNode msg, List dests) - { - super(source, src, msg, dests); - } - - public LNode project(AstFactory af, Role self) - { - Role srcrole = this.src.toName(); - List destroles = this.getDestinationRoles(); - LNode projection = null; - if (srcrole.equals(self) || destroles.contains(self)) - { - RoleNode src = (RoleNode) af.SimpleNameNode(this.src.getSource(), RoleKind.KIND, this.src.toName().toString()); // clone? - MessageNode msg = (MessageNode) this.msg.project(af); // FIXME: need namespace prefix update? - List dests = - this.getDestinations().stream().map((rn) -> - (RoleNode) af.SimpleNameNode(rn.getSource(), RoleKind.KIND, rn.toName().toString())).collect(Collectors.toList()); - if (srcrole.equals(self)) - { - projection = af.LSend(this.source, src, msg, dests); - } - if (destroles.contains(self)) - { - if (projection == null) - { - projection = af.LReceive(this.source, src, msg, dests); - } - else - { - LReceive lr = af.LReceive(this.source, src, msg, dests); - List lis = Arrays.asList(new LInteractionNode[]{(LInteractionNode) projection, lr}); - projection = af.LInteractionSeq(this.source, lis); - } - } - } - return projection; - } - - - @Override - protected GMessageTransfer copy() - { - return new GMessageTransfer(this.source, this.src, this.msg, getDestinations()); - } - - @Override - public GMessageTransfer clone(AstFactory af) - { - RoleNode src = this.src.clone(af); - MessageNode msg = this.msg.clone(af); - List dests = ScribUtil.cloneList(af, getDestinations()); - return af.GMessageTransfer(this.source, src, msg, dests); - } - - @Override - public GMessageTransfer reconstruct(RoleNode src, MessageNode msg, List dests) - { - ScribDel del = del(); - GMessageTransfer gmt = new GMessageTransfer(this.source, src, msg, dests); - gmt = (GMessageTransfer) gmt.del(del); - return gmt; - } - - @Override - public String toString() - { - return this.msg + " " + Constants.FROM_KW + " " + this.src + " " + Constants.TO_KW + " " - + getDestinations().stream().map(dest -> dest.toString()).collect(Collectors.joining(", ")) + ";"; - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Global getKind() - { - return GSimpleInteractionNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GNode.java b/scribble-core/src/main/java/org/scribble/ast/global/GNode.java deleted file mode 100644 index 56f327cc7..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GNode.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ProtocolKindNode; -import org.scribble.type.kind.Global; - -public interface GNode extends ProtocolKindNode -{ - @Override - default boolean isGlobal() - { - return true; - } - - @Override - default Global getKind() - { - return Global.KIND; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GParallel.java b/scribble-core/src/main/java/org/scribble/ast/global/GParallel.java deleted file mode 100644 index c6e52ca2b..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GParallel.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Parallel; -import org.scribble.ast.ProtocolBlock; -import org.scribble.ast.ScribNodeBase; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.Global; - -public class GParallel extends Parallel implements GCompoundInteractionNode -{ - public GParallel(CommonTree source, List blocks) - { - super(source, blocks); - } - - @Override - protected ScribNodeBase copy() - { - return new GParallel(this.source, getBlocks()); - } - - @Override - public GParallel clone(AstFactory af) - { - //List blocks = ScribUtil.cloneList(getBlocks()); - throw new RuntimeException("TODO: " + this); - } - - @Override - public GParallel reconstruct(List> blocks) - { - ScribDel del = del(); - GParallel gp = new GParallel(this.source, castBlocks(blocks)); - gp = (GParallel) gp.del(del); - return gp; - } - - @Override - public List getBlocks() - { - return castBlocks(super.getBlocks()); - } - - private static List castBlocks(List> blocks) - { - return blocks.stream().map((b) -> (GProtocolBlock) b).collect(Collectors.toList()); - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Global getKind() - { - return GCompoundInteractionNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GProtocolBlock.java b/scribble-core/src/main/java/org/scribble/ast/global/GProtocolBlock.java deleted file mode 100644 index c3092f49b..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GProtocolBlock.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.InteractionSeq; -import org.scribble.ast.ProtocolBlock; -import org.scribble.ast.local.LInteractionSeq; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.Global; -import org.scribble.type.name.Role; - -public class GProtocolBlock extends ProtocolBlock implements GNode -{ - public GProtocolBlock(CommonTree source, GInteractionSeq seq) - { - super(source, seq); - } - - public LProtocolBlock project(AstFactory af, Role self, LInteractionSeq seq) - { - LProtocolBlock projection = af.LProtocolBlock(this.source, seq); - return projection; - } - - @Override - protected GProtocolBlock copy() - { - return new GProtocolBlock(this.source, getInteractionSeq()); - } - - @Override - public GProtocolBlock clone(AstFactory af) - { - GInteractionSeq gis = getInteractionSeq().clone(af); - return af.GProtocolBlock(this.source, gis); - } - - @Override - public GProtocolBlock reconstruct(InteractionSeq seq) - { - ScribDel del = del(); - GProtocolBlock gpb = new GProtocolBlock(this.source, (GInteractionSeq) seq); - gpb = (GProtocolBlock) gpb.del(del); - return gpb; - } - - @Override - public GInteractionSeq getInteractionSeq() - { - return (GInteractionSeq) this.seq; - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Global getKind() - { - return GNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GProtocolDecl.java b/scribble-core/src/main/java/org/scribble/ast/global/GProtocolDecl.java deleted file mode 100644 index 6cb136bcb..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GProtocolDecl.java +++ /dev/null @@ -1,113 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Module; -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ProtocolDef; -import org.scribble.ast.ProtocolHeader; -import org.scribble.ast.local.LProjectionDecl; -import org.scribble.ast.local.LProtocolDef; -import org.scribble.ast.local.LProtocolHeader; -import org.scribble.del.ScribDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.Global; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.ModuleName; -import org.scribble.type.name.Role; - -public class GProtocolDecl extends ProtocolDecl implements GNode -{ - public GProtocolDecl(CommonTree source, List modifiers, GProtocolHeader header, GProtocolDef def) - { - super(source, modifiers, header, def); - } - - // FIXME: project modifiers? - public LProjectionDecl project(AstFactory af, Module mod, Role self, LProtocolHeader hdr, LProtocolDef def) throws ScribbleException // mod is just the parent? - { - /*//Role self = proj.peekSelf(); - GProtocolHeader gph = getHeader(); - LProtocolNameNode pn = Projector.makeProjectedSimpleNameNode(af, gph.getSource(), gph.getDeclName(), self); - - // Move to delegates? -- maybe fully integrate into projection pass - RoleDeclList roledecls = this.header.roledecls.project(af, self); - NonRoleParamDeclList paramdecls = this.header.paramdecls.project(af, self); - LProtocolHeader lph = af.LProtocolHeader(this.header.getSource(), pn, roledecls, paramdecls);*/ - GProtocolName gpn = this.getFullMemberName(mod); - LProjectionDecl proj = af.LProjectionDecl(this.source, this.modifiers, gpn, self, hdr, def); - return proj; - } - - @Override - protected GProtocolDecl copy() - { - return new GProtocolDecl(this.source, this.modifiers, getHeader(), getDef()); - } - - @Override - public GProtocolDecl clone(AstFactory af) - { - GProtocolHeader header = getHeader().clone(af); - GProtocolDef def = getDef().clone(af); - return af.GProtocolDecl(this.source, this.modifiers, header, def); - } - - @Override - public GProtocolDecl reconstruct(ProtocolHeader header, ProtocolDef def) - { - - ScribDel del = del(); - GProtocolDecl gpd = new GProtocolDecl(this.source, this.modifiers, (GProtocolHeader) header, (GProtocolDef) def); - gpd = (GProtocolDecl) gpd.del(del); // FIXME: does another shallow copy - return gpd; - } - - @Override - public GProtocolHeader getHeader() - { - return (GProtocolHeader) this.header; - } - - @Override - public GProtocolDef getDef() - { - return (GProtocolDef) this.def; - } - - @Override - public GProtocolName getFullMemberName(Module mod) - { - ModuleName fullmodname = mod.getFullModuleName(); - return new GProtocolName(fullmodname, this.header.getDeclName()); - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public boolean isGlobal() - { - return GNode.super.isGlobal(); - } - - // FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Global getKind() - { - return GNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GProtocolDef.java b/scribble-core/src/main/java/org/scribble/ast/global/GProtocolDef.java deleted file mode 100644 index 661822e2f..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GProtocolDef.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.ProtocolBlock; -import org.scribble.ast.ProtocolDef; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.ast.local.LProtocolDef; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.Global; -import org.scribble.type.name.Role; - -public class GProtocolDef extends ProtocolDef implements GNode -{ - public GProtocolDef(CommonTree source, GProtocolBlock block) - { - super(source, block); - } - - @Override - protected GProtocolDef copy() - { - return new GProtocolDef(this.source, getBlock()); - } - - public LProtocolDef project(AstFactory af, Role self, LProtocolBlock block) - { - LProtocolDef projection = af.LProtocolDef(this.source, block); - return projection; - } - - @Override - public GProtocolDef clone(AstFactory af) - { - GProtocolBlock block = getBlock().clone(af); - return af.GProtocolDef(this.source, block); - } - - @Override - public GProtocolDef reconstruct(ProtocolBlock block) - { - ScribDel del = del(); - GProtocolDef gpd = new GProtocolDef(this.source, (GProtocolBlock) block); - gpd = (GProtocolDef) gpd.del(del); - return gpd; - } - - @Override - public GProtocolBlock getBlock() - { - return (GProtocolBlock) this.block; - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Global getKind() - { - return GNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GProtocolHeader.java b/scribble-core/src/main/java/org/scribble/ast/global/GProtocolHeader.java deleted file mode 100644 index 992dcb811..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GProtocolHeader.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Constants; -import org.scribble.ast.NonRoleParamDeclList; -import org.scribble.ast.ProtocolHeader; -import org.scribble.ast.RoleDeclList; -import org.scribble.ast.ScribNodeBase; -import org.scribble.ast.local.LProtocolHeader; -import org.scribble.ast.name.qualified.GProtocolNameNode; -import org.scribble.ast.name.qualified.LProtocolNameNode; -import org.scribble.ast.name.qualified.ProtocolNameNode; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.Global; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.Role; - -public class GProtocolHeader extends ProtocolHeader implements GNode -{ - public GProtocolHeader(CommonTree source, GProtocolNameNode name, RoleDeclList roledecls, NonRoleParamDeclList paramdecls) - { - super(source, name, roledecls, paramdecls); - } - - @Override - protected ScribNodeBase copy() - { - return new GProtocolHeader(this.source, getNameNode(), this.roledecls, this.paramdecls); - } - - @Override - public GProtocolHeader clone(AstFactory af) - { - GProtocolNameNode name = getNameNode().clone(af); - RoleDeclList roledecls = this.roledecls.clone(af); - NonRoleParamDeclList paramdecls = this.paramdecls.clone(af); - return af.GProtocolHeader(this.source, name, roledecls, paramdecls); - } - - @Override - public GProtocolHeader reconstruct(ProtocolNameNode name, RoleDeclList rdl, NonRoleParamDeclList pdl) - { - ScribDel del = del(); - GProtocolHeader gph = new GProtocolHeader(this.source, (GProtocolNameNode) name, rdl, pdl); - gph = (GProtocolHeader) gph.del(del); - return gph; - } - - @Override - public GProtocolNameNode getNameNode() - { - return (GProtocolNameNode) this.name; - } - - @Override - public GProtocolName getDeclName() - { - return (GProtocolName) super.getDeclName(); - } - - // FIXME: make a delegate and move there? - public LProtocolHeader project(AstFactory af, Role self, LProtocolNameNode name, RoleDeclList roledecls, NonRoleParamDeclList paramdecls) - { - return af.LProtocolHeader(this.source, name, roledecls, paramdecls); - } - - @Override - public String toString() - { - return Constants.GLOBAL_KW + " " + super.toString(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GRecursion.java b/scribble-core/src/main/java/org/scribble/ast/global/GRecursion.java deleted file mode 100644 index 001552cda..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GRecursion.java +++ /dev/null @@ -1,182 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.ConnectionAction; -import org.scribble.ast.Do; -import org.scribble.ast.MessageTransfer; -import org.scribble.ast.ProtocolBlock; -import org.scribble.ast.Recursion; -import org.scribble.ast.local.LChoice; -import org.scribble.ast.local.LContinue; -import org.scribble.ast.local.LInteractionNode; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.ast.local.LRecursion; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.Global; -import org.scribble.type.name.RecVar; -import org.scribble.type.name.Role; - - -public class GRecursion extends Recursion implements GCompoundInteractionNode -{ - public GRecursion(CommonTree source, RecVarNode recvar, GProtocolBlock block) - { - super(source, recvar, block); - } - - public LRecursion project(AstFactory af, Role self, LProtocolBlock block) - { - RecVarNode recvar = this.recvar.clone(af); - LRecursion projection = null; - Set rvs = new HashSet<>(); - rvs.add(recvar.toName()); - LProtocolBlock pruned = prune(af, block, rvs); - if (!pruned.isEmpty()) - { - projection = af.LRecursion(this.source, recvar, pruned); - } - return projection; - } - - // Pruning must be considered here (at Recursion) due to unguarded recvars - // Set should be unnecessary (singleton OK) -- *nested* irrelevant continues should already have been pruned - // FIXME? refactor and separate into dels? -- maybe not: since pruning is a bit too much of a "centralised algorithm" -- currently relying on TODO exception for unhandled cases - protected static LProtocolBlock prune(AstFactory af, LProtocolBlock block, Set rvs) // FIXME: Set unnecessary - { - if (block.isEmpty()) - { - return block; - } - List lis = block.getInteractionSeq().getInteractions(); - if (lis.size() > 1) - { - return block; - } - else //if (lis.size() == 1) - { - // Only pruning if single statement body: if more than 1, must be some (non-empty?) statement before a continue -- cannot (shouldn't?) be a continue followed by some other statement due to reachability - LInteractionNode lin = lis.get(0); - if (lin instanceof LContinue) - { - if (rvs.contains(((LContinue) lin).recvar.toName())) - { - // FIXME: need equivalent for projection-irrelevant recursive-do in a protocoldecl - return af.LProtocolBlock(block.getSource(), - af.LInteractionSeq(block.seq.getSource(), Collections.emptyList())); - } - else - { - return block; - } - } - else if (lin instanceof MessageTransfer || lin instanceof Do || lin instanceof ConnectionAction) - { - return block; - } - else - { - if (lin instanceof LChoice) - { - List pruned = new LinkedList(); - for (LProtocolBlock b : ((LChoice) lin).getBlocks()) - { - if (!prune(af, b, rvs).isEmpty()) - { - pruned.add(b); - } - } - if (pruned.isEmpty()) - { - return af.LProtocolBlock(block.getSource(), - af.LInteractionSeq(block.seq.getSource(), Collections.emptyList())); - } - else - { - return af.LProtocolBlock(block.getSource(), - af.LInteractionSeq(block.seq.getSource(), Arrays.asList( - af.LChoice(lin.getSource(), ((LChoice) lin).subj, pruned)))); - } - } - else if (lin instanceof LRecursion) - { - rvs = new HashSet<>(rvs); - //rvs.add(((LRecursion) lin).recvar.toName()); // Set unnecessary - LProtocolBlock pruned = prune(af, ((LRecursion) lin).getBlock(), rvs); // Need to check if the current rec has any cases to prune in the nested rec (already pruned, but for the nested recvars only) - if (pruned.isEmpty()) - { - return pruned; - } - else - { - return af.LProtocolBlock(block.getSource(), - af.LInteractionSeq(block.seq.getSource(), Arrays.asList( - af.LRecursion(lin.getSource(), ((LRecursion) lin).recvar, pruned)))); - } - /*if (((LRecursion) lin).block.isEmpty()) - { - return AstFactoryImpl.FACTORY.LProtocolBlock(AstFactoryImpl.FACTORY.LInteractionSeq(Arrays.asList(AstFactoryImpl.FACTORY.LRecursion(((LRecursion) lin).recvar, ((LRecursion) lin).getBlock())))); - } - else - { - return ((LRecursion) lin).getBlock(); - }*/ - } - else - { - throw new RuntimeException("TODO: " + lin); - } - } - } - } - - @Override - protected GRecursion copy() - { - return new GRecursion(this.source, this.recvar, getBlock()); - } - - @Override - public GRecursion clone(AstFactory af) - { - RecVarNode recvar = this.recvar.clone(af); - GProtocolBlock block = getBlock().clone(af); - return af.GRecursion(this.source, recvar, block); - } - - @Override - public GRecursion reconstruct(RecVarNode recvar, ProtocolBlock block) - { - ScribDel del = del(); - GRecursion gr = new GRecursion(this.source, recvar, (GProtocolBlock) block); - gr = (GRecursion) gr.del(del); - return gr; - } - - @Override - public GProtocolBlock getBlock() - { - return (GProtocolBlock) this.block; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GSimpleInteractionNode.java b/scribble-core/src/main/java/org/scribble/ast/global/GSimpleInteractionNode.java deleted file mode 100644 index 717dad138..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GSimpleInteractionNode.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 GSimpleInteractionNode extends GInteractionNode -{ - -} diff --git a/scribble-core/src/main/java/org/scribble/ast/global/GWrap.java b/scribble-core/src/main/java/org/scribble/ast/global/GWrap.java deleted file mode 100644 index 94fbba094..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/global/GWrap.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.ConnectionAction; -import org.scribble.ast.Constants; -import org.scribble.ast.MessageNode; -import org.scribble.ast.MessageSigNode; -import org.scribble.ast.local.LNode; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.Global; -import org.scribble.type.kind.RoleKind; -import org.scribble.type.name.Role; - -public class GWrap extends ConnectionAction implements GSimpleInteractionNode -{ - - //public GWrap(CommonTree source, RoleNode src, RoleNode dest) - public GWrap(CommonTree source, MessageSigNode unit, RoleNode src, RoleNode dest) - { - super(source, src, unit, dest); - } - - public LNode project(AstFactory af, Role self) - { - Role srcrole = this.src.toName(); - Role destrole = this.dest.toName(); - LNode projection = null; - if (srcrole.equals(self) || destrole.equals(self)) - { - RoleNode src = (RoleNode) af.SimpleNameNode(this.src.getSource(), RoleKind.KIND, this.src.toName().toString()); // clone? - RoleNode dest = (RoleNode) af.SimpleNameNode(this.dest.getSource(), RoleKind.KIND, this.dest.toName().toString()); - if (srcrole.equals(self)) - { - projection = af.LWrapClient(this.source, src, dest); // src and dest (not self and peer) - } - if (destrole.equals(self)) - { - projection = af.LWrapServer(this.source, src, dest); - } - } - return projection; - } - - @Override - protected GWrap copy() - { - return new GWrap(this.source, (MessageSigNode) this.msg, this.src, this.dest); - } - - @Override - public GWrap clone(AstFactory af) - { - RoleNode src = this.src.clone(af); - RoleNode dest = this.dest.clone(af); - return af.GWrap(this.source, src, dest); - } - - @Override - public GWrap reconstruct(RoleNode src, MessageNode msg, RoleNode dest) - //public GWrap reconstruct(RoleNode src, RoleNode dest) - { - ScribDel del = del(); - GWrap gc = new GWrap(this.source, (MessageSigNode) this.msg, src, dest); //this.msg); - gc = (GWrap) gc.del(del); - return gc; - } - - @Override - public String toString() - { - return Constants.WRAP_KW + " " + this.src + " " + Constants.TO_KW + " " + this.dest + ";"; - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Global getKind() - { - return GSimpleInteractionNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LAccept.java b/scribble-core/src/main/java/org/scribble/ast/local/LAccept.java deleted file mode 100644 index 4979a34bb..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LAccept.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Collections; -import java.util.Set; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Constants; -import org.scribble.ast.MessageNode; -import org.scribble.ast.ScribNodeBase; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ScribDel; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; -import org.scribble.type.name.Role; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -public class LAccept extends LConnectionAction implements LSimpleInteractionNode -{ - public LAccept(CommonTree source, RoleNode src, MessageNode msg, RoleNode dest) - //public LAccept(RoleNode src, RoleNode dest) - { - super(source, src, msg, dest); - //super(src, dest); - } - - @Override - protected ScribNodeBase copy() - { - return new LAccept(this.source, this.src, this.msg, this.dest); - //return new LAccept(this.src, this.dest); - } - - @Override - public LAccept clone(AstFactory af) - { - RoleNode src = this.src.clone(af); - MessageNode msg = this.msg.clone(af); - RoleNode dest = this.dest.clone(af); - return af.LAccept(this.source, src, msg, dest); - //return AstFactoryImpl.FACTORY.LAccept(src, dest); - } - - @Override - public LAccept reconstruct(RoleNode src, MessageNode msg, RoleNode dest) - //public LAccept reconstruct(RoleNode src, RoleNode dest) - { - ScribDel del = del(); - LAccept lr = new LAccept(this.source, src, msg, dest); - //LAccept lr = new LAccept(src, dest); - lr = (LAccept) lr.del(del); - return lr; - } - - @Override - public Role inferLocalChoiceSubject(ProjectedChoiceSubjectFixer fixer) - { - fixer.setChoiceSubject(this.src.toName()); - return this.src.toName(); - } - - @Override - public String toString() - { - return (isUnitMessage() ? "" : this.msg + " ") + Constants.ACCEPT_KW + " " + this.src + ";"; - } - - @Override - public LInteractionNode merge(AstFactory af, LInteractionNode ln) throws ScribbleException - { - throw new RuntimeScribbleException("Invalid merge on LAccept: " + this); - } - - @Override - public boolean canMerge(LInteractionNode ln) - { - return false; - } - - @Override - public Set getEnabling() - { - return Collections.emptySet(); - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Local getKind() - { - return LSimpleInteractionNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LCatches.java b/scribble-core/src/main/java/org/scribble/ast/local/LCatches.java deleted file mode 100644 index 32e03e9c8..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LCatches.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Set; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.MessageNode; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; - -public class LCatches extends LInterrupt -{ - protected LCatches(CommonTree source, RoleNode src, List msgs) - { - super(source, src, msgs); - } - - @Override - public LInteractionNode merge(AstFactory af, LInteractionNode ln) throws ScribbleException - { - throw new RuntimeException("TODO: " + this); - } - - @Override - public boolean canMerge(LInteractionNode ln) - { - throw new RuntimeException("TODO: " + this); - } - - @Override - public Set getEnabling() - { - throw new RuntimeException("TODO: " + this); - } - - /*public LocalCatches(CommonTree ct, RoleNode src, List msgs, List dests) - { - this(ct, src, msgs, dests, null, null); - } - - protected LocalCatches(CommonTree ct, RoleNode src, List msgs, List dests, GlobalInterruptContext gicontext, Env env) - { - super(ct, src, msgs, dests, gicontext, env); - } - - @Override - protected LocalThrows reconstruct(CommonTree ct, RoleNode src, List msgs, List dests, GlobalInterruptContext icontext, Env env) - { - return new LocalThrows(ct, src, msgs, dests, icontext, env); - } - - /*@Override - public LocalCatches visitChildren(NodeVisitor nv) throws ScribbleException - { - LocalInterrupt interr = super.visitChildren(nv); - return new LocalCatches(interr.ct, interr.src, interr.msgs, interr.dests, (GlobalInterruptContext) interr.getContext()); - }* / - - @Override - public String toString() - { - String s = AntlrConstants.CATCHES_KW + " " + this.msgs.get(0).toString(); - for (MessageNode msg : this.msgs.subList(1, this.msgs.size())) - { - s += ", " + msg; - } - return s + " " + AntlrConstants.FROM_KW + " " + this.src.toName() + ";"; - } - - /*@Override - public void toGraph(GraphBuilder gb) - { - throw new RuntimeException("Shouldn't get in here."); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LChoice.java b/scribble-core/src/main/java/org/scribble/ast/local/LChoice.java deleted file mode 100644 index 68b176d2c..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LChoice.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Choice; -import org.scribble.ast.ProtocolBlock; -import org.scribble.ast.ScribNodeBase; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ScribDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; -import org.scribble.type.kind.Local; -import org.scribble.type.name.Role; -import org.scribble.util.ScribUtil; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -public class LChoice extends Choice implements LCompoundInteractionNode -{ - public LChoice(CommonTree source, RoleNode subj, List blocks) - { - super(source, subj, blocks); - } - - @Override - protected ScribNodeBase copy() - { - return new LChoice(this.source, this.subj, getBlocks()); - } - - @Override - public LChoice clone(AstFactory af) - { - RoleNode subj = this.subj.clone(af); - List blocks = ScribUtil.cloneList(af, getBlocks()); - return af.LChoice(this.source, subj, blocks); - } - - @Override - public LChoice reconstruct(RoleNode subj, List> blocks) - { - ScribDel del = del(); - LChoice lc = new LChoice(this.source, subj, castBlocks(blocks)); - lc = (LChoice) lc.del(del); - return lc; - } - - @Override - public List getBlocks() - { - return castBlocks(super.getBlocks()); - } - - @Override - public Role inferLocalChoiceSubject(ProjectedChoiceSubjectFixer fixer) - { - // Relies on: will never be inferring from a "continue X;" -- if choice is first statement in seq, continue must be guarded; if continue is not guarded, choice cannot be first statement in seq - return getBlocks().get(0).getInteractionSeq().getInteractions().get(0).inferLocalChoiceSubject(fixer); - } - - private static List castBlocks(List> blocks) - { - return blocks.stream().map((b) -> (LProtocolBlock) b).collect(Collectors.toList()); - } - - @Override - public LChoice merge(AstFactory af, LInteractionNode ln) throws ScribbleException - { - if (!(ln instanceof LChoice) || !this.canMerge(ln)) - { - throw new ScribbleException("Cannot merge " + this.getClass() + " and " + ln.getClass() + ": " + this + ", " + ln); - } - LChoice them = ((LChoice) ln); - /*if (!this.subj.toName().equals(them.subj.toName())) // NO: pointless, always DummyProjectionRoleNode at this point -- maybe unnecessary? - { - throw new ScribbleException("Cannot merge choices for " + this.subj + " and " + them.subj + ": " + this + ", " + ln); - }*/ - List blocks = new LinkedList<>(); - getBlocks().forEach(b -> blocks.add(b.clone(af))); - them.getBlocks().forEach(b -> blocks.add(b.clone(af))); - return af.LChoice(this.source, this.subj, blocks); // Not reconstruct: leave context building to post-projection passes - // Hacky: this.source - } - - @Override - public boolean canMerge(LInteractionNode ln) - { - // Merge currently does "nothing"; validation takes direct non-deterministic interpretation -- purpose of syntactic merge is to convert non-det to "equivalent" safe det in certain sitations - return ln instanceof LChoice; - } - - @Override - public Set getEnabling() - { - return getBlocks().stream().flatMap((b) -> b.getEnabling().stream()).collect(Collectors.toSet()); - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Local getKind() - { - return LCompoundInteractionNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LCompoundInteractionNode.java b/scribble-core/src/main/java/org/scribble/ast/local/LCompoundInteractionNode.java deleted file mode 100644 index f539aac6a..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LCompoundInteractionNode.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 LCompoundInteractionNode extends LInteractionNode -{ - -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LConnectionAction.java b/scribble-core/src/main/java/org/scribble/ast/local/LConnectionAction.java deleted file mode 100644 index 1b48dc421..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LConnectionAction.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.ConnectionAction; -import org.scribble.ast.MessageNode; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.type.kind.Local; - -public abstract class LConnectionAction extends ConnectionAction implements LSimpleInteractionNode -{ - public LConnectionAction(CommonTree source, RoleNode src, MessageNode msg, RoleNode dest) - { - super(source, src, msg, dest); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LContinue.java b/scribble-core/src/main/java/org/scribble/ast/local/LContinue.java deleted file mode 100644 index fc7514d03..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LContinue.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Collections; -import java.util.Set; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Continue; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.del.ScribDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; -import org.scribble.type.kind.Local; -import org.scribble.type.name.Role; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -public class LContinue extends Continue implements LSimpleInteractionNode -{ - public LContinue(CommonTree source, RecVarNode recvar) - { - super(source, recvar); - } - - @Override - protected LContinue copy() - { - return new LContinue(this.source, this.recvar); - } - - @Override - public LContinue clone(AstFactory af) - { - RecVarNode rv = this.recvar.clone(af); - return af.LContinue(this.source, rv); - } - - @Override - public LContinue reconstruct(RecVarNode recvar) - { - ScribDel del = del(); - LContinue lc = new LContinue(this.source, recvar); - lc = (LContinue) lc.del(del); - return lc; - } - - @Override - public Role inferLocalChoiceSubject(ProjectedChoiceSubjectFixer fixer) - { - //return new DummyProjectionRoleNode().toName(); // For e.g. rec X { 1() from A to B; choice at A { continue X; } or { 2() from A to B; } } - return fixer.createRecVarRole(this.recvar.toName()); // Never used? - //return null; - } - - @Override - public LInteractionNode merge(AstFactory af, LInteractionNode ln) throws ScribbleException - { - if (!(ln instanceof LContinue) || !this.canMerge(ln)) - { - throw new ScribbleException("Cannot merge " + this.getClass() + " and " + ln.getClass() + ": " + this + ", " + ln); - } - LContinue them = ((LContinue) ln); - if (!this.recvar.equals(them.recvar)) - { - throw new ScribbleException("Cannot merge choices for " + this.recvar + " and " + them.recvar + ": " + this + ", " + ln); - } - return clone(af); - } - - @Override - public boolean canMerge(LInteractionNode ln) - { - return ln instanceof LContinue; - } - - @Override - public Set getEnabling() - { - return Collections.emptySet(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LDelegationElem.java b/scribble-core/src/main/java/org/scribble/ast/local/LDelegationElem.java deleted file mode 100644 index c156d6d65..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LDelegationElem.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.UnaryPayloadElem; -import org.scribble.ast.name.qualified.LProtocolNameNode; -import org.scribble.del.ScribDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.Local; -import org.scribble.type.name.PayloadElemType; -import org.scribble.visit.AstVisitor; - -// N.B. extends UnaryPayloadElem, not DelegationElem -public class LDelegationElem extends UnaryPayloadElem -{ - // Currently no potential for ambiguity because only generated, not parsed - public LDelegationElem(CommonTree source, LProtocolNameNode proto) - { - super(source, proto); - } - - @Override - public boolean isLocalDelegationElem() - { - return true; - } - - @Override - protected LDelegationElem copy() - { - return new LDelegationElem(this.source, (LProtocolNameNode) this.name); - } - - @Override - public LDelegationElem clone(AstFactory af) - { - LProtocolNameNode name = (LProtocolNameNode) this.name.clone(af); - return af.LDelegationElem(this.source, name); - } - - public LDelegationElem reconstruct(LProtocolNameNode proto) - { - ScribDel del = del(); - LDelegationElem elem = new LDelegationElem(this.source, proto); - elem = (LDelegationElem) elem.del(del); - return elem; - } - - @Override - public LDelegationElem visitChildren(AstVisitor nv) throws ScribbleException - { - LProtocolNameNode name = (LProtocolNameNode) visitChild(this.name, nv); - return reconstruct(name); - } - - /*@Override - public String toString() - { - return this.proto + "@" + this.role; - }*/ - - @Override - //public PayloadType toPayloadType() - public PayloadElemType toPayloadType() - { - return this.name.toPayloadType(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LDisconnect.java b/scribble-core/src/main/java/org/scribble/ast/local/LDisconnect.java deleted file mode 100644 index 36461678a..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LDisconnect.java +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.HashSet; -import java.util.Set; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Constants; -import org.scribble.ast.MessageNode; -import org.scribble.ast.MessageSigNode; -import org.scribble.ast.ScribNodeBase; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ScribDel; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; -import org.scribble.type.name.Role; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -public class LDisconnect extends LConnectionAction implements LSimpleInteractionNode -{ - public final RoleNode self; // super.src - public final RoleNode peer; // super.dest - - public LDisconnect(CommonTree source, MessageSigNode unit, RoleNode self, RoleNode peer) - { - //super(source, self, GDisconnect.UNIT_MESSAGE_SIG_NODE, peer); - super(source, self, unit, peer); - this.self = self; - this.peer = peer; - } - - @Override - protected ScribNodeBase copy() - { - return new LDisconnect(this.source, (MessageSigNode) this.msg, this.self, this.peer); - } - - @Override - public LDisconnect clone(AstFactory af) - { - RoleNode self = this.self.clone(af); - RoleNode peer = this.peer.clone(af); - return af.LDisconnect(this.source, self, peer); - } - - @Override - public LDisconnect reconstruct(RoleNode src, MessageNode msg, RoleNode dest) - //public LDisconnect reconstruct(RoleNode self, RoleNode peer) - { - ScribDel del = del(); - LDisconnect lr = new LDisconnect(this.source, (MessageSigNode) this.msg, this.self, this.peer); - lr = (LDisconnect) lr.del(del); - return lr; - } - - @Override - public Role inferLocalChoiceSubject(ProjectedChoiceSubjectFixer fixer) - { - fixer.setChoiceSubject(this.self.toName()); - return this.self.toName(); - } - - @Override - public String toString() - { - return Constants.DISCONNECT_KW + " " + this.peer + ";"; - } - - @Override - public LInteractionNode merge(AstFactory af, LInteractionNode ln) throws ScribbleException - { - throw new RuntimeScribbleException("Invalid merge on LDisconnect: " + this); - } - - @Override - public boolean canMerge(LInteractionNode ln) - { - return false; - } - - @Override - public Set getEnabling() - { - Set enab = new HashSet<>(); - //enab.add(this.msg.toMessage()); // Return empty to skip over this in LInteractionSeq - return enab; - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Local getKind() - { - return LSimpleInteractionNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LDo.java b/scribble-core/src/main/java/org/scribble/ast/local/LDo.java deleted file mode 100644 index 3e195f22f..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LDo.java +++ /dev/null @@ -1,124 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Collections; -import java.util.Iterator; -import java.util.Set; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Do; -import org.scribble.ast.NonRoleArgList; -import org.scribble.ast.RoleArgList; -import org.scribble.ast.context.ModuleContext; -import org.scribble.ast.name.qualified.LProtocolNameNode; -import org.scribble.ast.name.qualified.ProtocolNameNode; -import org.scribble.del.ScribDel; -import org.scribble.main.JobContext; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; -import org.scribble.type.kind.Local; -import org.scribble.type.name.LProtocolName; -import org.scribble.type.name.Role; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -public class LDo extends Do implements LSimpleInteractionNode -{ - public LDo(CommonTree source, RoleArgList roleinstans, NonRoleArgList arginstans, LProtocolNameNode proto) - { - super(source, roleinstans, arginstans, proto); - } - - @Override - protected LDo copy() - { - return new LDo(this.source, this.roles, this.args, getProtocolNameNode()); - } - - @Override - public LDo clone(AstFactory af) - { - RoleArgList roles = this.roles.clone(af); - NonRoleArgList args = this.args.clone(af); - LProtocolNameNode proto = this.getProtocolNameNode().clone(af); - return af.LDo(this.source, roles, args, proto); - } - - @Override - public LDo reconstruct(RoleArgList roles, NonRoleArgList args, ProtocolNameNode proto) - { - ScribDel del = del(); - LDo ld = new LDo(this.source, roles, args, (LProtocolNameNode) proto); - ld = (LDo) ld.del(del); - return ld; - } - - @Override - public LProtocolNameNode getProtocolNameNode() - { - return (LProtocolNameNode) this.proto; - } - - @Override - public LProtocolName getTargetProtocolDeclFullName(ModuleContext mcontext) - { - return (LProtocolName) super.getTargetProtocolDeclFullName(mcontext); - } - - @Override - public LProtocolDecl getTargetProtocolDecl(JobContext jcontext, ModuleContext mcontext) - { - return (LProtocolDecl) super.getTargetProtocolDecl(jcontext, mcontext); - } - - @Override - public Role inferLocalChoiceSubject(ProjectedChoiceSubjectFixer fixer) - { - ModuleContext mc = fixer.getModuleContext(); - JobContext jc = fixer.job.getContext(); - Role subj = getTargetProtocolDecl(jc, mc).getDef().getBlock() - .getInteractionSeq().getInteractions().get(0).inferLocalChoiceSubject(fixer); - // FIXME: need equivalent of (e.g) rec X { continue X; } pruning (cf GRecursion.prune) for irrelevant recursive-do (e.g. proto(A, B, C) { choice at A {A->B.do Proto(A,B,C)} or {A->B.B->C} })) - Iterator roleargs = this.roles.getRoles().iterator(); - for (Role decl : getTargetProtocolDecl(jc, mc).header.roledecls.getRoles()) - { - Role arg = roleargs.next(); - if (decl.equals(subj)) - { - return arg; - } - } - throw new RuntimeException("Shouldn't get here: " + this); - } - - @Override - public LInteractionNode merge(AstFactory af, LInteractionNode ln) throws ScribbleException - { - throw new RuntimeScribbleException("Invalid merge on LDo: " + this); - } - - @Override - public boolean canMerge(LInteractionNode ln) - { - return false; - } - - @Override - public Set getEnabling() - { - return Collections.emptySet(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LInteractionNode.java b/scribble-core/src/main/java/org/scribble/ast/local/LInteractionNode.java deleted file mode 100644 index 9dbcaf4fc..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LInteractionNode.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Set; - -import org.scribble.ast.AstFactory; -import org.scribble.ast.InteractionNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; -import org.scribble.type.kind.Local; -import org.scribble.type.name.Role; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -// Alternatively to interface, use GlobalNode subclass with delegation to "super" base (e.g. Choice) classes -public interface LInteractionNode extends InteractionNode, LNode -{ - Role inferLocalChoiceSubject(ProjectedChoiceSubjectFixer fixer); - - // "merge" currently does "nothing"; validation takes direct non-deterministic interpretation -- purpose of syntactic merge would be to convert non-det to "equivalent" safe det in certain sitations - LInteractionNode merge(AstFactory af, LInteractionNode ln) throws ScribbleException; - boolean canMerge(LInteractionNode ln); - - Set getEnabling(); -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LInteractionSeq.java b/scribble-core/src/main/java/org/scribble/ast/local/LInteractionSeq.java deleted file mode 100644 index 1c23d7c2c..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LInteractionSeq.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Collections; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.InteractionNode; -import org.scribble.ast.InteractionSeq; -import org.scribble.ast.ScribNodeBase; -import org.scribble.del.ScribDel; -import org.scribble.type.Message; -import org.scribble.type.kind.Local; -import org.scribble.util.ScribUtil; - -public class LInteractionSeq extends InteractionSeq implements LNode -{ - public LInteractionSeq(CommonTree source, List lis) - { - super(source, lis); - } - - @Override - protected ScribNodeBase copy() - { - return new LInteractionSeq(this.source, getInteractions()); - } - - @Override - public LInteractionSeq clone(AstFactory af) - { - List lis = ScribUtil.cloneList(af, getInteractions()); - return af.LInteractionSeq(this.source, lis); - } - - @Override - public LInteractionSeq reconstruct(List> actions) - { - ScribDel del = del(); - LInteractionSeq lis = new LInteractionSeq(this.source, castNodes(actions)); - lis = (LInteractionSeq) lis.del(del); - return lis; - } - - @Override - public List getInteractions() - { - return castNodes(super.getInteractions()); - } - - @Override - public boolean isLocal() - { - return true; - } - - private static List castNodes(List> nodes) - { - return nodes.stream().map((n) -> (LInteractionNode) n).collect(Collectors.toList()); - } - - public Set getEnabling() - { - if (!this.isEmpty()) - { - for (LInteractionNode ln : getInteractions()) - { - Set enab = ln.getEnabling(); - if (!enab.isEmpty()) - { - return enab; - } - } - } - return Collections.emptySet(); - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Local getKind() - { - return LNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LInterrupt.java b/scribble-core/src/main/java/org/scribble/ast/local/LInterrupt.java deleted file mode 100644 index 86b8cd8e3..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LInterrupt.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.Interrupt; -import org.scribble.ast.MessageNode; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.type.name.Role; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -public abstract class LInterrupt extends Interrupt implements LSimpleInteractionNode -{ - protected LInterrupt(CommonTree source, RoleNode src, List msgs) - { - super(source, src, msgs); - } - - @Override - public Role inferLocalChoiceSubject(ProjectedChoiceSubjectFixer fixer) - { - throw new RuntimeException("TODO: " + this); - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Local getKind() - { - return LSimpleInteractionNode.super.getKind(); - }*/ - - - - - - /*public final List dests; - - /*public LocalInterrupt(CommonTree ct, RoleNode src, List msgs, List dests) - { - this(ct, src, msgs, dests, null, null); - }* / - - protected LocalInterrupt(CommonTree ct, RoleNode src, List msgs, List dests, GlobalInterruptContext gicontext, Env env) - { - super(ct, src, msgs, gicontext, env); - this.dests = new LinkedList<>(dests); - } - - /* //@Override - protected LocalInterrupt reconstruct(CommonTree ct, RoleNode src, List msgs, List dests, GlobalInterruptContext icontext, Env env) - { - return new LocalInterrupt(ct, src, msgs, dests, icontext, env); - }* / - protected abstract LocalInterrupt reconstruct(CommonTree ct, RoleNode src, List msgs, List dests, GlobalInterruptContext icontext, Env env); - - @Override - public LocalInterrupt leaveContextBuilding(NodeContextBuilder builder) throws ScribbleException - { - LocalInterrupt intt = (LocalInterrupt) super.leaveContextBuilding(builder); - GlobalInterruptContext icontext = - new GlobalInterruptContext(intt.dests.stream().map((rn) -> rn.toName()).collect(Collectors.toList())); - //return new LocalInterrupt(intt.ct, intt.src, intt.msgs, intt.dests, icontext); - return reconstruct(intt.ct, intt.src, intt.msgs, intt.dests, icontext, getEnv()); - } - - @Override - public LocalInterrupt visitChildren(NodeVisitor nv) throws ScribbleException - { - RoleNode src = (RoleNode) visitChild(this.src, nv); - List msgs = new LinkedList<>(); - for (MessageNode msg : this.msgs) - { - msgs.add((MessageNode) visitChild(msg, nv)); - } - List dests = new LinkedList(); - for (RoleNode dest : this.dests) - { - dests.add((RoleNode) visitChild(dest, nv)); - } - //return new LocalInterrupt(this.ct, src, msgs, this.dests, getContext()); - return reconstruct(this.ct, src, msgs, this.dests, getContext(), getEnv()); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LInterruptible.java b/scribble-core/src/main/java/org/scribble/ast/local/LInterruptible.java deleted file mode 100644 index 8e664abdb..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LInterruptible.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Set; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Interruptible; -import org.scribble.ast.ProtocolBlock; -import org.scribble.ast.ScribNodeBase; -import org.scribble.ast.name.simple.ScopeNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; -import org.scribble.type.kind.Local; -import org.scribble.type.kind.ScopeKind; -import org.scribble.type.name.Name; -import org.scribble.type.name.Role; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -//public class LocalInterruptible extends Interruptible implements LocalInteractionNode -public class LInterruptible extends Interruptible implements LCompoundInteractionNode -{ - //protected LocalInterruptible(ScopeNode scope, LocalProtocolBlock block, List interrs) - protected LInterruptible(CommonTree source, ScopeNode scope, ProtocolBlock block, List interrs) - { - super(source, scope, block, interrs); - } - - @Override - protected ScribNodeBase copy() - { - throw new RuntimeException("TODO: " + this); - } - - @Override - public LInterruptible clone(AstFactory af) - { - throw new RuntimeException("TODO: " + this); - } - - @Override - public boolean isEmptyScope() - { - throw new RuntimeException("TODO: " + this); - } - - @Override - public Name getScopeElement() - { - throw new RuntimeException("TODO: " + this); - } - - @Override - public Role inferLocalChoiceSubject(ProjectedChoiceSubjectFixer fixer) - { - throw new RuntimeException("TODO: " + this); - } - - @Override - public LInteractionNode merge(AstFactory af, LInteractionNode ln) throws ScribbleException - { - throw new RuntimeException("TODO: " + this); - } - - @Override - public boolean canMerge(LInteractionNode ln) - { - throw new RuntimeException("TODO: " + this); - } - - @Override - public Set getEnabling() - { - throw new RuntimeException("TODO: " + this); - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Local getKind() - { - return LCompoundInteractionNode.super.getKind(); - }*/ - - - - - - - /*public LocalInterruptible(CommonTree ct, ScopeNode scope, LocalProtocolBlock block, LocalThrows thro, List cats) - { - this(ct, scope, block, compileInterrupts(thro, cats), null, null); - } - - /*public LocalInterruptible(CommonTree ct, ScopeNode scope, LocalProtocolBlock block, List interrs, CompoundInteractionNodeContext icontext) - { - super(ct, scope, block, interrs, icontext); - }* / - - protected LocalInterruptible(CommonTree ct, ScopeNode scope, LocalProtocolBlock block, List interrs, CompoundInteractionNodeContext icontext, Env env) - { - super(ct, scope, block, interrs, icontext, env); - } - - private static List compileInterrupts(LocalThrows thro, List cats) - { - List interrs = new LinkedList<>(); - if (thro != null) - { - interrs.add(thro); - } - interrs.addAll(cats); - return interrs; - } - - @Override - protected LocalInterruptible reconstruct(CommonTree ct, ScopeNode scope, LocalProtocolBlock block, List interrs, CompoundInteractionNodeContext icontext, Env env) - { - return new LocalInterruptible(ct, scope, block, interrs, icontext, env); - } - - @Override - public LocalInterruptible leaveGraphBuilding(GraphBuilder builder) - { - throw new RuntimeException("TODO: "); - } - - /*@Override - public LocalInterruptible leaveContextBuilding(Node parent, NodeContextBuilder builder) throws ScribbleException - { - Interruptible intt = super.leaveContextBuilding(parent, builder); - return new LocalInterruptible(intt.ct, intt.scope, intt.block, interrs, (CompoundInteractionNodeContext) intt.getContext()); - } - - @Override - public LocalInterruptible leaveWFChoiceCheck(WellFormedChoiceChecker checker) throws ScribbleException - { - Interruptible intt = super.leaveWFChoiceCheck(checker); - return new LocalInterruptible(intt.ct, intt.scope, intt.block, intt.interrs, (CompoundInteractionNodeContext) intt.getContext(), intt.getEnv()); - } - - @Override - public LocalInterruptible visitChildren(NodeVisitor nv) throws ScribbleException - { - Interruptible intt = super.visitChildren(nv); - return new LocalInterruptible(intt.ct, intt.scope, intt.block, intt.interrs, intt.getContext(), intt.getEnv()); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LMessageTransfer.java b/scribble-core/src/main/java/org/scribble/ast/local/LMessageTransfer.java deleted file mode 100644 index 37da5e4dc..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LMessageTransfer.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.MessageNode; -import org.scribble.ast.MessageTransfer; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.type.kind.Local; - -public abstract class LMessageTransfer extends MessageTransfer implements LSimpleInteractionNode -{ - public LMessageTransfer(CommonTree source, RoleNode src, MessageNode msg, List dests) - { - super(source, src, msg, dests); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LNode.java b/scribble-core/src/main/java/org/scribble/ast/local/LNode.java deleted file mode 100644 index 452759784..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LNode.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ProtocolKindNode; -import org.scribble.type.kind.Local; - -public interface LNode extends ProtocolKindNode -{ - @Override - default boolean isLocal() - { - return true; - } - - @Override - default Local getKind() - { - return Local.KIND; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LParallel.java b/scribble-core/src/main/java/org/scribble/ast/local/LParallel.java deleted file mode 100644 index b21a50c8b..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LParallel.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Set; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Parallel; -import org.scribble.ast.ProtocolBlock; -import org.scribble.ast.ScribNodeBase; -import org.scribble.del.ScribDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; -import org.scribble.type.kind.Local; -import org.scribble.type.name.Role; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -public class LParallel extends Parallel implements LCompoundInteractionNode -{ - public LParallel(CommonTree source, List blocks) - { - super(source, blocks); - } - - @Override - protected ScribNodeBase copy() - { - return new LParallel(this.source, getBlocks()); - } - - @Override - public LParallel clone(AstFactory af) - { - //List<:ProtocolBlock> blocks = ScribUtil.cloneList(getBlocks()); - throw new RuntimeException("TODO: " + this); - } - - @Override - public LParallel reconstruct(List> blocks) - { - ScribDel del = del(); - LParallel lp = new LParallel(this.source, castBlocks(blocks)); - lp = (LParallel) lp.del(del); - return lp; - } - - @Override - public List getBlocks() - { - return castBlocks(super.getBlocks()); - } - - @Override - public Role inferLocalChoiceSubject(ProjectedChoiceSubjectFixer fixer) - { - return getBlocks().get(0).getInteractionSeq().getInteractions().get(0).inferLocalChoiceSubject(fixer); - } - - private static List castBlocks(List> blocks) - { - return blocks.stream().map((b) -> (LProtocolBlock) b).collect(Collectors.toList()); - } - - @Override - public LInteractionNode merge(AstFactory af, LInteractionNode ln) throws ScribbleException - { - throw new RuntimeException("TODO: " + this); - } - - @Override - public boolean canMerge(LInteractionNode ln) - { - throw new RuntimeException("TODO: " + this); - } - - @Override - public Set getEnabling() - { - throw new RuntimeException("TODO: " + this); - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Local getKind() - { - return LCompoundInteractionNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LProjectionDecl.java b/scribble-core/src/main/java/org/scribble/ast/local/LProjectionDecl.java deleted file mode 100644 index c17555ffd..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LProjectionDecl.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.ProtocolDef; -import org.scribble.ast.ProtocolHeader; -import org.scribble.ast.ScribNodeBase; -import org.scribble.del.ScribDel; -import org.scribble.del.local.LProjectionDeclDel; -import org.scribble.type.kind.Local; - -public class LProjectionDecl extends LProtocolDecl -{ - public LProjectionDecl(CommonTree source, List modifiers, LProtocolHeader header, LProtocolDef def) - { - super(source, modifiers, header, def); - } - - @Override - protected ScribNodeBase copy() - { - return new LProjectionDecl(this.source, this.modifiers, getHeader(), getDef()); - } - - @Override - public LProjectionDecl clone(AstFactory af) - { - LProtocolHeader header = getHeader().clone(af); - LProtocolDef def = getDef().clone(af); - LProjectionDeclDel del = (LProjectionDeclDel) del(); - return af.LProjectionDecl(this.source, this.modifiers, del.getSourceProtocol(), del.getSelfRole(), header, def); - } - - @Override - public LProjectionDecl reconstruct(ProtocolHeader header, ProtocolDef def) - { - ScribDel del = del(); - LProjectionDecl lpd = new LProjectionDecl(this.source, this.modifiers, (LProtocolHeader) header, (LProtocolDef) def); - lpd = (LProjectionDecl) lpd.del(del); - return lpd; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LProtocolBlock.java b/scribble-core/src/main/java/org/scribble/ast/local/LProtocolBlock.java deleted file mode 100644 index 9eef61f4b..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LProtocolBlock.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Set; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.InteractionSeq; -import org.scribble.ast.ProtocolBlock; -import org.scribble.del.ScribDel; -import org.scribble.type.Message; -import org.scribble.type.kind.Local; - -public class LProtocolBlock extends ProtocolBlock implements LNode -{ - public LProtocolBlock(CommonTree source, LInteractionSeq seq) - { - super(source, seq); - } - - @Override - protected LProtocolBlock copy() - { - return new LProtocolBlock(this.source, getInteractionSeq()); - } - - @Override - public LProtocolBlock clone(AstFactory af) - { - LInteractionSeq lis = getInteractionSeq().clone(af); - return af.LProtocolBlock(this.source, lis); - } - - @Override - public LProtocolBlock reconstruct(InteractionSeq seq) - { - ScribDel del = del(); - LProtocolBlock lpb = new LProtocolBlock(this.source, (LInteractionSeq) seq); - lpb = (LProtocolBlock) lpb.del(del); - return lpb; - } - - @Override - public LInteractionSeq getInteractionSeq() - { - return (LInteractionSeq) this.seq; - } - - public LProtocolBlock merge(LProtocolBlock lpb) - { - throw new RuntimeException("TODO: " + this + ", " + lpb); - } - - public Set getEnabling() - { - return getInteractionSeq().getEnabling(); - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Local getKind() - { - return LNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LProtocolDecl.java b/scribble-core/src/main/java/org/scribble/ast/local/LProtocolDecl.java deleted file mode 100644 index 8894b6743..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LProtocolDecl.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Module; -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ProtocolDef; -import org.scribble.ast.ProtocolHeader; -import org.scribble.ast.ScribNodeBase; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.Local; -import org.scribble.type.name.LProtocolName; -import org.scribble.type.name.ModuleName; -import org.scribble.type.name.Role; - -// Maybe make abstract with concrete parsed (LParsedDecl) and projected (LProjectionDecl) subclasses -public class LProtocolDecl extends ProtocolDecl implements LNode -{ - public LProtocolDecl(CommonTree source, List modifiers, LProtocolHeader header, LProtocolDef def) - { - super(source, modifiers, header, def); - } - - @Override - protected ScribNodeBase copy() - { - return new LProtocolDecl(this.source, this.modifiers, getHeader(), getDef()); - } - - @Override - public LProtocolDecl clone(AstFactory af) - { - LProtocolHeader header = getHeader().clone(af); - LProtocolDef def = getDef().clone(af); - return af.LProtocolDecl(this.source, this.modifiers, header, def); - } - - @Override - public LProtocolDecl reconstruct(ProtocolHeader header, ProtocolDef def) - { - ScribDel del = del(); - LProtocolDecl lpd = new LProtocolDecl(this.source, this.modifiers, (LProtocolHeader) header, (LProtocolDef) def); - lpd = (LProtocolDecl) lpd.del(del); - return lpd; - } - - @Override - public LProtocolHeader getHeader() - { - return (LProtocolHeader) this.header; - } - - @Override - public LProtocolDef getDef() - { - return (LProtocolDef) this.def; - } - - @Override - public LProtocolName getFullMemberName(Module mod) - { - ModuleName fullmodname = mod.getFullModuleName(); - return new LProtocolName(fullmodname, this.header.getDeclName()); - } - - public Role getSelfRole() - { - return getHeader().getSelfRole(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LProtocolDef.java b/scribble-core/src/main/java/org/scribble/ast/local/LProtocolDef.java deleted file mode 100644 index 9166056bd..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LProtocolDef.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.ProtocolBlock; -import org.scribble.ast.ProtocolDef; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.Local; - -public class LProtocolDef extends ProtocolDef implements LNode -{ - public LProtocolDef(CommonTree source, LProtocolBlock block) - { - super(source, block); - } - - @Override - protected LProtocolDef copy() - { - return new LProtocolDef(this.source, getBlock()); - } - - @Override - public LProtocolDef clone(AstFactory af) - { - LProtocolBlock block = getBlock().clone(af); - return af.LProtocolDef(this.source, block); - } - - @Override - public LProtocolDef reconstruct(ProtocolBlock block) - { - ScribDel del = del(); - LProtocolDef lpd = new LProtocolDef(this.source, (LProtocolBlock) block); - lpd = (LProtocolDef) lpd.del(del); - return lpd; - } - - @Override - public LProtocolBlock getBlock() - { - return (LProtocolBlock) this.block; - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Local getKind() - { - return LNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LProtocolHeader.java b/scribble-core/src/main/java/org/scribble/ast/local/LProtocolHeader.java deleted file mode 100644 index 58216baa3..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LProtocolHeader.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Constants; -import org.scribble.ast.NameDeclNode; -import org.scribble.ast.NonRoleParamDeclList; -import org.scribble.ast.ProtocolHeader; -import org.scribble.ast.RoleDecl; -import org.scribble.ast.RoleDeclList; -import org.scribble.ast.ScribNodeBase; -import org.scribble.ast.name.qualified.LProtocolNameNode; -import org.scribble.ast.name.qualified.ProtocolNameNode; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.Local; -import org.scribble.type.kind.RoleKind; -import org.scribble.type.name.LProtocolName; -import org.scribble.type.name.Role; - -public class LProtocolHeader extends ProtocolHeader implements LNode -{ - public LProtocolHeader(CommonTree source, LProtocolNameNode name, RoleDeclList roledecls, NonRoleParamDeclList paramdecls) - { - super(source, name, roledecls, paramdecls); - } - - @Override - protected ScribNodeBase copy() - { - return new LProtocolHeader(this.source, getNameNode(), this.roledecls, this.paramdecls); - } - - @Override - public LProtocolHeader clone(AstFactory af) - { - LProtocolNameNode name = getNameNode().clone(af); - RoleDeclList roledecls = this.roledecls.clone(af); - NonRoleParamDeclList paramdecls = this.paramdecls.clone(af); - return af.LProtocolHeader(this.source, name, roledecls, paramdecls); - } - - @Override - public LProtocolHeader reconstruct(ProtocolNameNode name, RoleDeclList rdl, NonRoleParamDeclList pdl) - { - ScribDel del = del(); - LProtocolHeader gph = new LProtocolHeader(this.source, (LProtocolNameNode) name, rdl, pdl); - gph = (LProtocolHeader) gph.del(del); - return gph; - } - - public Role getSelfRole() - { - for (NameDeclNode rd : this.roledecls.getDecls()) - { - RoleDecl tmp = (RoleDecl) rd; - if (tmp.isSelfRoleDecl()) - { - return tmp.getDeclName(); - } - } - throw new RuntimeException("Shouldn't get here: " + this.roledecls); - } - - @Override - public LProtocolNameNode getNameNode() - { - return (LProtocolNameNode) this.name; - } - - @Override - public LProtocolName getDeclName() - { - return (LProtocolName) super.getDeclName(); - } - - @Override - public String toString() - { - return Constants.LOCAL_KW + " " + super.toString(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LReceive.java b/scribble-core/src/main/java/org/scribble/ast/local/LReceive.java deleted file mode 100644 index 5cf1cfc92..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LReceive.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.HashSet; -import java.util.List; -import java.util.Set; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Constants; -import org.scribble.ast.MessageNode; -import org.scribble.ast.ScribNodeBase; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ScribDel; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; -import org.scribble.type.name.Role; -import org.scribble.util.ScribUtil; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -public class LReceive extends LMessageTransfer implements LSimpleInteractionNode -{ - public LReceive(CommonTree source, RoleNode src, MessageNode msg, List dests) - { - super(source, src, msg, dests); - } - - @Override - protected ScribNodeBase copy() - { - return new LReceive(this.source, this.src, this.msg, getDestinations()); - } - - @Override - public LReceive clone(AstFactory af) - { - RoleNode src = this.src.clone(af); - MessageNode msg = this.msg.clone(af); - List dests = ScribUtil.cloneList(af, getDestinations()); - return af.LReceive(this.source, src, msg, dests); - } - - @Override - public LReceive reconstruct(RoleNode src, MessageNode msg, List dests) - { - ScribDel del = del(); - LReceive lr = new LReceive(this.source, src, msg, dests); - lr = (LReceive) lr.del(del); - return lr; - } - - @Override - public Role inferLocalChoiceSubject(ProjectedChoiceSubjectFixer fixer) - { - fixer.setChoiceSubject(this.src.toName()); - return this.src.toName(); - } - - @Override - public String toString() - { - return this.msg + " " + Constants.FROM_KW + " " + this.src + ";"; - } - - @Override - public LInteractionNode merge(AstFactory af, LInteractionNode ln) throws ScribbleException - { - throw new RuntimeScribbleException("Invalid merge on LReceive: " + this); - } - - @Override - public boolean canMerge(LInteractionNode ln) - { - return false; - } - - @Override - public Set getEnabling() - { - Set enab = new HashSet<>(); - enab.add(this.msg.toMessage()); - return enab; - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Local getKind() - { - return LSimpleInteractionNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LRecursion.java b/scribble-core/src/main/java/org/scribble/ast/local/LRecursion.java deleted file mode 100644 index 3ed2457f0..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LRecursion.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Set; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.ProtocolBlock; -import org.scribble.ast.Recursion; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.del.ScribDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; -import org.scribble.type.kind.Local; -import org.scribble.type.name.Role; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -public class LRecursion extends Recursion implements LCompoundInteractionNode -{ - public LRecursion(CommonTree source, RecVarNode recvar, LProtocolBlock block) - { - super(source, recvar, block); - } - - @Override - protected LRecursion copy() - { - return new LRecursion(this.source, this.recvar, getBlock()); - } - - @Override - public LRecursion reconstruct(RecVarNode recvar, ProtocolBlock block) - { - ScribDel del = del(); - LRecursion lr = new LRecursion(this.source, recvar, (LProtocolBlock) block); - lr = (LRecursion) lr.del(del); - return lr; - } - - @Override - public LRecursion clone(AstFactory af) - { - RecVarNode recvar = this.recvar.clone(af); - LProtocolBlock block = getBlock().clone(af); - return af.LRecursion(this.source, recvar, block); - } - - @Override - public LProtocolBlock getBlock() - { - return (LProtocolBlock) this.block; - } - - @Override - public Role inferLocalChoiceSubject(ProjectedChoiceSubjectFixer fixer) - { - //fixer.pushRec(this.recvar.toName()); - return getBlock().getInteractionSeq().getInteractions().get(0).inferLocalChoiceSubject(fixer); - } - - @Override - public LInteractionNode merge(AstFactory af, LInteractionNode ln) throws ScribbleException - { - if (!(ln instanceof LRecursion) || !this.canMerge(ln)) - { - throw new ScribbleException("Cannot merge " + this.getClass() + " and " + ln.getClass() + ": " + this + ", " + ln); - } - LRecursion them = ((LRecursion) ln); - if (!this.recvar.equals(them.recvar)) - { - throw new ScribbleException("Cannot merge recursions for " + this.recvar + " and " + them.recvar + ": " + this + ", " + ln); - } - return af.LRecursion(this.source, this.recvar.clone(af), getBlock().merge(them.getBlock())); // Not reconstruct: leave context building to post-projection passes - // HACK: this source - } - - @Override - public boolean canMerge(LInteractionNode ln) - { - return ln instanceof LRecursion; - } - - @Override - public Set getEnabling() - { - return getBlock().getEnabling(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LRequest.java b/scribble-core/src/main/java/org/scribble/ast/local/LRequest.java deleted file mode 100644 index 33636538f..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LRequest.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Collections; -import java.util.Set; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Constants; -import org.scribble.ast.MessageNode; -import org.scribble.ast.ScribNodeBase; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ScribDel; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; -import org.scribble.type.name.Role; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -public class LRequest extends LConnectionAction implements LSimpleInteractionNode -{ - public LRequest(CommonTree source, RoleNode src, MessageNode msg, RoleNode dest) - //public LConnect(RoleNode src, RoleNode dest) - { - super(source, src, msg, dest); - //super(src, dest); - } - - @Override - protected ScribNodeBase copy() - { - return new LRequest(this.source, this.src, this.msg, this.dest); - //return new LConnect(this.src, this.dest); - } - - @Override - public LRequest clone(AstFactory af) - { - RoleNode src = this.src.clone(af); - MessageNode msg = this.msg.clone(af); - RoleNode dest = this.dest.clone(af); - return af.LConnect(this.source, src, msg, dest); - //return AstFactoryImpl.FACTORY.LConnect(src, dest); - } - - @Override - public LRequest reconstruct(RoleNode src, MessageNode msg, RoleNode dest) - //public LConnect reconstruct(RoleNode src, RoleNode dest) - { - ScribDel del = del(); - LRequest ls = new LRequest(this.source, src, msg, dest); - //LConnect ls = new LConnect(src, dest); - ls = (LRequest) ls.del(del); - return ls; - } - - // Could make a LMessageTransfer to factor this out with LReceive - @Override - public Role inferLocalChoiceSubject(ProjectedChoiceSubjectFixer fixer) - { - return this.src.toName(); - //throw new RuntimeException("TODO: " + this); - } - - @Override - public String toString() - { - return (isUnitMessage() ? "" : this.msg+ " ") + Constants.CONNECT_KW + " " + this.dest.toString() + ";"; - } - - @Override - public LInteractionNode merge(AstFactory af, LInteractionNode ln) throws ScribbleException - { - throw new RuntimeScribbleException("Invalid merge on LConnect: " + this); - } - - @Override - public boolean canMerge(LInteractionNode ln) - { - return false; - } - - @Override - public Set getEnabling() - { - return Collections.emptySet(); - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Local getKind() - { - return LSimpleInteractionNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LSend.java b/scribble-core/src/main/java/org/scribble/ast/local/LSend.java deleted file mode 100644 index 5b56a2409..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LSend.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Collections; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Constants; -import org.scribble.ast.MessageNode; -import org.scribble.ast.ScribNodeBase; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ScribDel; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; -import org.scribble.type.name.Role; -import org.scribble.util.ScribUtil; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -public class LSend extends LMessageTransfer - implements LSimpleInteractionNode // Explicitly needed here for getKind -{ - public LSend(CommonTree source, RoleNode src, MessageNode msg, List dests) - { - super(source, src, msg, dests); - } - - @Override - protected ScribNodeBase copy() - { - return new LSend(this.source, this.src, this.msg, getDestinations()); - } - - @Override - public LSend clone(AstFactory af) - { - RoleNode src = this.src.clone(af); - MessageNode msg = this.msg.clone(af); - List dests = ScribUtil.cloneList(af, getDestinations()); - return af.LSend(this.source, src, msg, dests); - } - - @Override - public LSend reconstruct(RoleNode src, MessageNode msg, List dests) - { - ScribDel del = del(); - LSend ls = new LSend(this.source, src, msg, dests); - ls = (LSend) ls.del(del); - return ls; - } - - // Could make a LMessageTransfer to factor this out with LReceive - @Override - public Role inferLocalChoiceSubject(ProjectedChoiceSubjectFixer fixer) - { - return this.src.toName(); - } - - @Override - public String toString() - { - return this.msg + " " + Constants.TO_KW + " " - + getDestinations().stream().map((dest) -> dest.toString()).collect(Collectors.joining(", ")) + ";"; - } - - @Override - public LInteractionNode merge(AstFactory af, LInteractionNode ln) throws ScribbleException - { - throw new RuntimeScribbleException("Invalid merge on LSend: " + this); - } - - @Override - public boolean canMerge(LInteractionNode ln) - { - return false; - } - - @Override - public Set getEnabling() - { - return Collections.emptySet(); - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Local getKind() - { - return LSimpleInteractionNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LSimpleInteractionNode.java b/scribble-core/src/main/java/org/scribble/ast/local/LSimpleInteractionNode.java deleted file mode 100644 index 42b645253..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LSimpleInteractionNode.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 LSimpleInteractionNode extends LInteractionNode -{ - -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LThrows.java b/scribble-core/src/main/java/org/scribble/ast/local/LThrows.java deleted file mode 100644 index 90bdc83eb..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LThrows.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Set; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.MessageNode; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; - -public class LThrows extends LInterrupt -{ - protected LThrows(CommonTree source, RoleNode src, List msgs) - { - super(source, src, msgs); - } - - @Override - public LInteractionNode merge(AstFactory af, LInteractionNode ln) throws ScribbleException - { - throw new RuntimeException("TODO: " + this); - } - - @Override - public boolean canMerge(LInteractionNode ln) - { - throw new RuntimeException("TODO: " + this); - } - - @Override - public Set getEnabling() - { - throw new RuntimeException("TODO: " + this); - } - - /*public LocalThrows(CommonTree ct, RoleNode src, List msgs, List dests) - { - this(ct, src, msgs, dests, null, null); - } - - protected LocalThrows(CommonTree ct, RoleNode src, List msgs, List dests, GlobalInterruptContext gicontext, Env env) - { - super(ct, src, msgs, dests, gicontext, env); - } - - @Override - protected LocalThrows reconstruct(CommonTree ct, RoleNode src, List msgs, List dests, GlobalInterruptContext icontext, Env env) - { - return new LocalThrows(ct, src, msgs, dests, icontext, env); - } - - /*@Override - public LocalThrows visitChildren(NodeVisitor nv) throws ScribbleException - { - LocalInterrupt interr = super.visitChildren(nv); - //return new LocalThrows(interr.ct, interr.src, interr.msgs, interr.dests, (GlobalInterruptContext) interr.getContext()); - return reconstruct(interr.ct, interr.src, interr.msgs, interr.dests, (GlobalInterruptContext) interr.getContext(), getEnv()); - }* / - - @Override - public String toString() - { - String s = AntlrConstants.THROWS_KW + " " + this.msgs.get(0).toString(); - for (MessageNode msg : this.msgs.subList(1, this.msgs.size())) - { - s += ", " + msg; - } - s += " " + AntlrConstants.TO_KW + " " + this.dests.get(0); - for (RoleNode dest : this.dests.subList(1, this.dests.size())) - { - s += ", " + dest.toName(); - } - return s + ";"; - } - - /*@Override - public void toGraph(GraphBuilder gb) - { - throw new RuntimeException("Shouldn't get in here."); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LWrapClient.java b/scribble-core/src/main/java/org/scribble/ast/local/LWrapClient.java deleted file mode 100644 index c9e70d83a..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LWrapClient.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Collections; -import java.util.Set; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Constants; -import org.scribble.ast.MessageNode; -import org.scribble.ast.MessageSigNode; -import org.scribble.ast.ScribNodeBase; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ScribDel; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; -import org.scribble.type.name.Role; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -public class LWrapClient extends LConnectionAction implements LSimpleInteractionNode -{ - public LWrapClient(CommonTree source, MessageSigNode unit, RoleNode src, RoleNode dest) - { - //super(source, src, GWrap.UNIT_MESSAGE_SIG_NODE, dest); - super(source, src, unit, dest); - } - - @Override - protected ScribNodeBase copy() - { - return new LWrapClient(this.source, (MessageSigNode) this.msg, this.src, this.dest); - } - - @Override - public LWrapClient clone(AstFactory af) - { - RoleNode src = this.src.clone(af); - RoleNode dest = this.dest.clone(af); - return af.LWrapClient(this.source, src, dest); - } - - @Override - public LWrapClient reconstruct(RoleNode src, MessageNode msg, RoleNode dest) - //public LWrapClient reconstruct(RoleNode src, RoleNode dest) - { - ScribDel del = del(); - LWrapClient ls = new LWrapClient(this.source, (MessageSigNode) this.msg, src, dest); - ls = (LWrapClient) ls.del(del); - return ls; - } - - // Could make a LMessageTransfer to factor this out with LReceive - @Override - public Role inferLocalChoiceSubject(ProjectedChoiceSubjectFixer fixer) - { - return this.src.toName(); - //throw new RuntimeException("TODO: " + this); - } - - @Override - public String toString() - { - return Constants.WRAP_KW + " " + Constants.TO_KW + " " + this.dest.toString() + ";"; - } - - @Override - public LInteractionNode merge(AstFactory af, LInteractionNode ln) throws ScribbleException - { - throw new RuntimeScribbleException("Invalid merge on LWrapClient: " + this); - } - - @Override - public boolean canMerge(LInteractionNode ln) - { - return false; - } - - @Override - public Set getEnabling() - { - return Collections.emptySet(); - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Local getKind() - { - return LSimpleInteractionNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/LWrapServer.java b/scribble-core/src/main/java/org/scribble/ast/local/LWrapServer.java deleted file mode 100644 index ffca9b18e..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/LWrapServer.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Collections; -import java.util.Set; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Constants; -import org.scribble.ast.MessageNode; -import org.scribble.ast.MessageSigNode; -import org.scribble.ast.ScribNodeBase; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ScribDel; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; -import org.scribble.type.name.Role; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -public class LWrapServer extends LConnectionAction implements LSimpleInteractionNode -{ - public LWrapServer(CommonTree source, MessageSigNode unit, RoleNode src, RoleNode dest) - { - super(source, src, unit, dest); - } - - @Override - protected ScribNodeBase copy() - { - return new LWrapServer(this.source, (MessageSigNode) this.msg, this.src, this.dest); - } - - @Override - public LWrapServer clone(AstFactory af) - { - RoleNode src = this.src.clone(af); - RoleNode dest = this.dest.clone(af); - return af.LWrapServer(this.source, src, dest); - } - - @Override - public LWrapServer reconstruct(RoleNode src, MessageNode msg, RoleNode dest) - //public LWrapServer reconstruct(RoleNode src, RoleNode dest) - { - ScribDel del = del(); - LWrapServer lr = new LWrapServer(this.source, (MessageSigNode) this.msg, src, dest); - lr = (LWrapServer) lr.del(del); - return lr; - } - - @Override - public Role inferLocalChoiceSubject(ProjectedChoiceSubjectFixer fixer) - { - fixer.setChoiceSubject(this.src.toName()); - return this.src.toName(); - } - - @Override - public String toString() - { - return Constants.WRAP_KW + " " + Constants.FROM_KW + " " + this.src + ";"; - } - - @Override - public LInteractionNode merge(AstFactory af, LInteractionNode ln) throws ScribbleException - { - throw new RuntimeScribbleException("Invalid merge on LWrapServer: " + this); - } - - @Override - public boolean canMerge(LInteractionNode ln) - { - return false; - } - - @Override - public Set getEnabling() - { - return Collections.emptySet(); - } - - /*// FIXME: shouldn't be needed, but here due to Eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=436350 - @Override - public Local getKind() - { - return LSimpleInteractionNode.super.getKind(); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/ast/local/SelfRoleDecl.java b/scribble-core/src/main/java/org/scribble/ast/local/SelfRoleDecl.java deleted file mode 100644 index 0f4c8cda4..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/local/SelfRoleDecl.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.RoleDecl; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.ast.name.simple.SimpleNameNode; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.RoleKind; -import org.scribble.type.name.Role; - -public class SelfRoleDecl extends RoleDecl -{ - public SelfRoleDecl(CommonTree source, RoleNode rn) - { - super(source, rn); - } - - @Override - protected SelfRoleDecl copy() - { - return new SelfRoleDecl(this.source, (RoleNode) this.name); - } - - @Override - public RoleDecl reconstruct(SimpleNameNode name) - { - ScribDel del = del(); - SelfRoleDecl rd = new SelfRoleDecl(this.source, (RoleNode) name); - rd = (SelfRoleDecl) rd.del(del); - return rd; - } - - @Override - public SelfRoleDecl project(AstFactory af, Role self) - { - throw new RuntimeException("Shouldn't get in here: " + this); - } - - @Override - public boolean isSelfRoleDecl() - { - return true; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/NameNode.java b/scribble-core/src/main/java/org/scribble/ast/name/NameNode.java deleted file mode 100644 index b52014d9b..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/NameNode.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Arrays; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.ScribNodeBase; -import org.scribble.type.kind.Kind; -import org.scribble.type.name.Named; - -// 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. names nodes of different kinds are still only compared syntactically) -public abstract class NameNode extends ScribNodeBase implements Named -{ - protected final String[] elems; - - public NameNode(CommonTree source, String... elems) - { - super(source); - this.elems = elems; - } - - @Override - public abstract NameNode clone(AstFactory af); - - public String[] getElements() - { - return Arrays.copyOf(this.elems, this.elems.length); - } - - public int getElementCount() - { - return this.elems.length; - } - - public boolean isEmpty() - { - return this.elems.length == 0; - } - - protected boolean isPrefixed() - { - return this.elems.length > 1; - } - - protected String[] getPrefixElements() - { - return Arrays.copyOfRange(this.elems, 0, this.elems.length - 1); - } - - protected String getLastElement() - { - return this.elems[this.elems.length - 1]; - } - - @Override - public boolean equals(Object o) // FIXME: should NameNodes ever be used in an equality checking context? (cf. other AST nodes) -- this work should be done using sesstype.Name instead? - { - if (this == o) - { - return true; - } - if (!(o instanceof NameNode)) - { - return false; - } - NameNode nn = (NameNode) o; - return nn.canEqual(this) && Arrays.equals(this.elems, nn.elems); - } - - public abstract boolean canEqual(Object o); - - @Override - public int hashCode() - { - int hash = 317; - hash = 31 * hash + this.elems.hashCode(); - return hash; - } - - @Override - public String toString() - { - return toName().toString(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/PayloadElemNameNode.java b/scribble-core/src/main/java/org/scribble/ast/name/PayloadElemNameNode.java deleted file mode 100644 index 09b8c1baf..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/PayloadElemNameNode.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.type.kind.PayloadTypeKind; -import org.scribble.type.name.PayloadElemType; - - -// 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 PayloadElemNameNode 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) - PayloadElemType toPayloadType(); -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/qualified/DataTypeNode.java b/scribble-core/src/main/java/org/scribble/ast/name/qualified/DataTypeNode.java deleted file mode 100644 index 4740e01db..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/qualified/DataTypeNode.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.name.PayloadElemNameNode; -import org.scribble.type.Arg; -import org.scribble.type.kind.DataTypeKind; -import org.scribble.type.name.DataType; - -//public class DataTypeNode extends MemberNameNode implements PayloadElemNameNode -public class DataTypeNode extends MemberNameNode implements PayloadElemNameNode -{ - public DataTypeNode(CommonTree source, String... elems) - { - super(source, elems); - } - - @Override - protected DataTypeNode copy() - { - return new DataTypeNode(this.source, this.elems); - } - - @Override - public DataTypeNode clone(AstFactory af) - { - return (DataTypeNode) af.QualifiedNameNode(this.source, DataTypeKind.KIND, this.elems); - } - - @Override - public DataType toName() - { - DataType membname = new DataType(getLastElement()); - return isPrefixed() - ? new DataType(getModuleNamePrefix(), membname) - : membname; - } - - @Override - public boolean isDataTypeNameNode() - { - return true; - } - - @Override - public Arg toArg() - { - return toPayloadType(); - } - - @Override - public DataType toPayloadType() - { - return toName(); - } - - @Override - public boolean equals(Object o) // FIXME: is equals/hashCode needed for these Nodes? - { - if (this == o) - { - return true; - } - if (!(o instanceof DataTypeNode)) - { - return false; - } - return ((DataTypeNode) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof DataTypeNode; - } - - @Override - public int hashCode() - { - int hash = 409; - hash = 31 * hash + this.elems.hashCode(); - return hash; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/qualified/GProtocolNameNode.java b/scribble-core/src/main/java/org/scribble/ast/name/qualified/GProtocolNameNode.java deleted file mode 100644 index edff75acd..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/qualified/GProtocolNameNode.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.type.kind.Global; -import org.scribble.type.name.GProtocolName; - -public class GProtocolNameNode extends ProtocolNameNode -{ - public GProtocolNameNode(CommonTree source, String... ns) - { - super(source, ns); - } - - @Override - protected GProtocolNameNode copy() - { - return new GProtocolNameNode(this.source, this.elems); - } - - @Override - public GProtocolNameNode clone(AstFactory af) - { - return (GProtocolNameNode) af.QualifiedNameNode(this.source, Global.KIND, this.elems); - } - - @Override - public GProtocolName toName() - { - GProtocolName membname = new GProtocolName(getLastElement()); - return isPrefixed() - ? new GProtocolName(getModuleNamePrefix(), membname) - : membname; - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof GProtocolNameNode)) - { - return false; - } - return ((GProtocolNameNode) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof GProtocolNameNode; - } - - @Override - public int hashCode() - { - int hash = 419; - hash = 31 * hash + this.elems.hashCode(); - return hash; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/qualified/LProtocolNameNode.java b/scribble-core/src/main/java/org/scribble/ast/name/qualified/LProtocolNameNode.java deleted file mode 100644 index 1cc702d85..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/qualified/LProtocolNameNode.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.name.PayloadElemNameNode; -import org.scribble.type.Arg; -import org.scribble.type.kind.Local; -import org.scribble.type.name.LProtocolName; - -public class LProtocolNameNode extends ProtocolNameNode implements PayloadElemNameNode -{ - public LProtocolNameNode(CommonTree source, String... ns) - { - super(source, ns); - } - - @Override - protected LProtocolNameNode copy() - { - return new LProtocolNameNode(this.source, this.elems); - } - - @Override - public LProtocolNameNode clone(AstFactory af) - { - return (LProtocolNameNode) af.QualifiedNameNode(this.source, Local.KIND, this.elems); - } - - @Override - public LProtocolName toName() - { - LProtocolName membname = new LProtocolName(getLastElement()); - return isPrefixed() - ? new LProtocolName(getModuleNamePrefix(), membname) - : membname; - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof LProtocolNameNode)) - { - return false; - } - return ((LProtocolNameNode) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof LProtocolNameNode; - } - - @Override - public int hashCode() - { - int hash = 421; - hash = 31 * hash + this.elems.hashCode(); - return hash; - } - - @Override - public Arg toArg() - { - return toPayloadType(); - } - - @Override - public LProtocolName toPayloadType() - { - return toName(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/qualified/MemberNameNode.java b/scribble-core/src/main/java/org/scribble/ast/name/qualified/MemberNameNode.java deleted file mode 100644 index 26dc1025b..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/qualified/MemberNameNode.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 org.antlr.runtime.tree.CommonTree; -import org.scribble.type.kind.Kind; -import org.scribble.type.name.ModuleName; -import org.scribble.type.name.PackageName; - -public abstract class MemberNameNode extends QualifiedNameNode -{ - public MemberNameNode(CommonTree source, String... ns) - { - super(source, ns); - } - - protected ModuleName getModuleNamePrefix() - { - String[] prefix = getPrefixElements(); - ModuleName mn = new ModuleName(prefix[prefix.length - 1]); - if (prefix.length == 1) - { - return mn; - } - return new ModuleName(new PackageName(Arrays.copyOf(prefix, prefix.length - 1)), mn); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/qualified/MessageSigNameNode.java b/scribble-core/src/main/java/org/scribble/ast/name/qualified/MessageSigNameNode.java deleted file mode 100644 index 0308973bf..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/qualified/MessageSigNameNode.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.MessageNode; -import org.scribble.type.kind.SigKind; -import org.scribble.type.name.MessageSigName; - -public class MessageSigNameNode extends MemberNameNode implements MessageNode -{ - public MessageSigNameNode(CommonTree source, String... elems) - { - super(source, elems); - } - - @Override - public MessageNode project(AstFactory af) - { - return this; - } - - @Override - protected MessageSigNameNode copy() - { - return new MessageSigNameNode(this.source, this.elems); - } - - @Override - public MessageSigNameNode clone(AstFactory af) - { - return (MessageSigNameNode) af.QualifiedNameNode(this.source, SigKind.KIND, this.elems); - } - - @Override - public MessageSigName toName() - { - MessageSigName membname = new MessageSigName(getLastElement()); - return isPrefixed() - ? new MessageSigName(getModuleNamePrefix(), membname) - : membname; - } - - @Override - public boolean isMessageSigNameNode() - { - return true; - } - - @Override - public MessageSigName toMessage() // Difference between toName and toMessage is scope? does that make sense? - { - return toName(); - } - - @Override - public MessageSigName toArg() - { - return toMessage(); - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof MessageSigNameNode)) - { - return false; - } - return ((MessageSigNameNode) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof MessageSigNameNode; - } - - @Override - public int hashCode() - { - int hash = 421; - hash = 31 * hash + this.elems.hashCode(); - return hash; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/qualified/ModuleNameNode.java b/scribble-core/src/main/java/org/scribble/ast/name/qualified/ModuleNameNode.java deleted file mode 100644 index 2580ceb05..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/qualified/ModuleNameNode.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.type.kind.ModuleKind; -import org.scribble.type.name.ModuleName; -import org.scribble.type.name.PackageName; - -public class ModuleNameNode extends QualifiedNameNode -{ - public ModuleNameNode(CommonTree source, String... ns) - { - super(source, ns); - } - - @Override - protected ModuleNameNode copy() - { - return new ModuleNameNode(this.source, this.elems); - } - - @Override - public ModuleNameNode clone(AstFactory af) - { - return (ModuleNameNode) af.QualifiedNameNode(this.source, ModuleKind.KIND, this.elems); - } - - @Override - public ModuleName toName() - { - ModuleName modname = new ModuleName(getLastElement()); - return isPrefixed() - ? new ModuleName(new PackageName(getPrefixElements()), modname) - : modname; - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof ModuleNameNode)) - { - return false; - } - return ((ModuleNameNode) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof ModuleNameNode; - } - - @Override - public int hashCode() - { - int hash = 409; - hash = 31 * hash + this.elems.hashCode(); - return hash; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/qualified/ProtocolNameNode.java b/scribble-core/src/main/java/org/scribble/ast/name/qualified/ProtocolNameNode.java deleted file mode 100644 index f2f1d6eda..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/qualified/ProtocolNameNode.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.ProtocolName; - -public abstract class ProtocolNameNode extends MemberNameNode -{ - public ProtocolNameNode(CommonTree source, String... ns) - { - super(source, ns); - } - - public abstract ProtocolName toName(); -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/qualified/QualifiedNameNode.java b/scribble-core/src/main/java/org/scribble/ast/name/qualified/QualifiedNameNode.java deleted file mode 100644 index a31a2d5b0..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/qualified/QualifiedNameNode.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.NameNode; -import org.scribble.type.kind.Kind; - -public abstract class QualifiedNameNode extends NameNode -{ - public QualifiedNameNode(CommonTree source, String... ns) - { - super(source, ns); - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/simple/AmbigNameNode.java b/scribble-core/src/main/java/org/scribble/ast/name/simple/AmbigNameNode.java deleted file mode 100644 index e1730d08c..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/simple/AmbigNameNode.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.MessageNode; -import org.scribble.ast.name.PayloadElemNameNode; -import org.scribble.type.Arg; -import org.scribble.type.Message; -import org.scribble.type.kind.AmbigKind; -import org.scribble.type.kind.DataTypeKind; -import org.scribble.type.kind.NonRoleArgKind; -import org.scribble.type.name.AmbigName; -import org.scribble.type.name.PayloadElemType; - -// 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) -// No counterpart needed for MessageNode because MessageSignature values can be syntactically distinguished from sig parameters -//public class AmbigNameNode extends SimpleNameNode implements MessageNode, PayloadElemNameNode -//public class AmbigNameNode extends SimpleNameNode implements MessageNode, PayloadElemNameNode -public class AmbigNameNode extends SimpleNameNode implements MessageNode, PayloadElemNameNode // Currently hardcoded to DataTypeKind for payload elems -{ - public AmbigNameNode(CommonTree source, String identifier) - { - super(source, identifier); - } - - @Override - public MessageNode project(AstFactory af) - { - throw new RuntimeException("Shouldn't get in here: " + this); - } - - @Override - protected AmbigNameNode copy() - { - return new AmbigNameNode(this.source, getIdentifier()); - } - - @Override - public AmbigNameNode clone(AstFactory af) - { - return (AmbigNameNode) af.AmbiguousNameNode(this.source, getIdentifier()); - } - - @Override - public Arg toArg() - { - throw new RuntimeException("Ambiguous name node not disambiguated: " + this); - } - - @Override - public Message toMessage() - { - throw new RuntimeException("Ambiguous name node not disambiguated: " + this); - } - - @Override - //public PayloadType toPayloadType() - public PayloadElemType toPayloadType() // As a payload elem, currently hardcoded to expect only DataTypeKind (protocol payloads not supported) - //public PayloadType toPayloadType() - { - throw new RuntimeException("Ambiguous name node not disambiguated: " + this); - } - - @Override - public AmbigName toName() - { - return new AmbigName(getIdentifier()); - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof AmbigNameNode)) - { - return false; - } - return ((AmbigNameNode) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof AmbigNameNode; - } - - @Override - public int hashCode() - { - int hash = 331; - hash = 31 * super.hashCode(); - return hash; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/simple/DummyProjectionRoleNode.java b/scribble-core/src/main/java/org/scribble/ast/name/simple/DummyProjectionRoleNode.java deleted file mode 100644 index a45b6257d..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/simple/DummyProjectionRoleNode.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.AstFactory; -import org.scribble.del.ScribDel; -import org.scribble.type.name.Role; -import org.scribble.visit.Substitutor; - -// For local choice subjects -public class DummyProjectionRoleNode extends RoleNode -{ - public static final String DUMMY_PROJECTION_ROLE = "__DUMMY_ROLE"; - - public DummyProjectionRoleNode() - { - super(null, DUMMY_PROJECTION_ROLE); - } - - @Override - protected DummyProjectionRoleNode copy() - { - return new DummyProjectionRoleNode(); - } - - @Override - public DummyProjectionRoleNode clone(AstFactory af) - { - return af.DummyProjectionRoleNode(); - } - - @Override - public DummyProjectionRoleNode substituteNames(Substitutor subs) - { - //throw new RuntimeException("Shouldn't get in here: " + this); - return reconstruct(null); // HACK: for ProjectedSubprotocolPruner, but maybe useful for others - } - - @Override - protected DummyProjectionRoleNode reconstruct(String identifier) - { - ScribDel del = del(); - DummyProjectionRoleNode rn = new DummyProjectionRoleNode(); - rn = (DummyProjectionRoleNode) rn.del(del); - return rn; - } - - @Override - public Role toName() - { - return new Role(getIdentifier()); - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof DummyProjectionRoleNode)) - { - return false; - } - return ((DummyProjectionRoleNode) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof DummyProjectionRoleNode; - } - - @Override - public int hashCode() - { - int hash = 359; - hash = 31 * super.hashCode(); - return hash; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/simple/NonRoleParamNode.java b/scribble-core/src/main/java/org/scribble/ast/name/simple/NonRoleParamNode.java deleted file mode 100644 index d7ca11b94..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/simple/NonRoleParamNode.java +++ /dev/null @@ -1,182 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.MessageNode; -import org.scribble.ast.NonRoleArgNode; -import org.scribble.ast.name.PayloadElemNameNode; -import org.scribble.type.Arg; -import org.scribble.type.Message; -import org.scribble.type.kind.DataTypeKind; -import org.scribble.type.kind.Kind; -import org.scribble.type.kind.NonRoleParamKind; -import org.scribble.type.kind.SigKind; -import org.scribble.type.name.DataType; -import org.scribble.type.name.MessageSigName; -import org.scribble.type.name.Name; -import org.scribble.type.name.PayloadElemType; -import org.scribble.visit.Substitutor; - -// An unambiguous kinded parameter (ambiguous parameters handled by disambiguation) that isn't a role -- e.g. DataType/MessageSigName param -//public class NonRoleParamNode extends SimpleNameNode implements MessageNode, PayloadElemNameNode -//public class NonRoleParamNode extends SimpleNameNode implements MessageNode, PayloadElemNameNode -public class NonRoleParamNode extends SimpleNameNode implements MessageNode, PayloadElemNameNode // As a payload, can only be a DataType (so hardcode) -{ - public final K kind; - - public NonRoleParamNode(CommonTree source, K kind, String identifier) - { - super(source, identifier); - this.kind = kind; - } - - @Override - public MessageNode project(AstFactory af) // MessageSigName params - { - return this; - } - - @Override - protected NonRoleParamNode copy() - { - return new NonRoleParamNode<>(this.source, this.kind, getIdentifier()); - } - - @Override - public NonRoleParamNode clone(AstFactory af) - { - return af.NonRoleParamNode(this.source, this.kind, getIdentifier()); - } - - @Override - public NonRoleArgNode substituteNames(Substitutor subs) - { - Arg arg = toArg(); - NonRoleArgNode an; - if (this.kind.equals(SigKind.KIND) || this.kind.equals(DataTypeKind.KIND)) - //if (this.kind instanceof NonRoleParamKind) // Would additionally include other payloadtype kinds - { - an = subs.getArgumentSubstitution(arg); // getArgumentSubstitution returns a clone - } - else - { - throw new RuntimeException("TODO: " + this); - } - // Effectively a reconstruct: use the dels/envs made by the subprotocolvisitor cloning, cf. RoleNode - an = (NonRoleArgNode) an.del(del()); - return an; - } - - @Override - public Name toName() - { - String id = getIdentifier(); - if (this.kind.equals(SigKind.KIND)) - { - return Kind.castName(this.kind, new MessageSigName(id)); - } - else if (this.kind.equals(DataTypeKind.KIND)) - { - return Kind.castName(this.kind, new DataType(id)); - } - else - { - throw new RuntimeException("Shouldn't get in here: " + this.kind); - } - } - - @Override - public boolean isParamNode() - { - return true; - } - - @Override - public Arg toArg() - { - Arg arg; - if (this.kind.equals(DataTypeKind.KIND)) // FIXME: as a payload kind, currently hardcorded to data type kinds (protocol payloads not supported) - { - arg = toPayloadType(); - } - else if (this.kind.equals(SigKind.KIND)) - { - arg = toMessage(); - } - else - { - throw new RuntimeException("Shouldn't get here: " + this); - } - @SuppressWarnings("unchecked") - Arg tmp = (Arg) arg; - return tmp; - } - - @Override - public Message toMessage() - { - if (!this.kind.equals(SigKind.KIND)) - { - throw new RuntimeException("Not a sig kind parameter: " + this); - } - return (Message) toName(); - } - - @Override - //public PayloadType toPayloadType() - public PayloadElemType toPayloadType() // Currently can assume the only possible kind for NonRoleParamNode is DataTypeKind - //public PayloadType toPayloadType() - { - if (this.kind.equals(DataTypeKind.KIND)) // As a payload, NonRoleParamNode can only be a DataType - { - return (DataType) toName(); - } - /*else if (this.kind.equals(Local.KIND)) // Protocol params not supported - { - return (Local) toName(); - }*/ - throw new RuntimeException("Not a payload kind parameter: " + this); - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof NonRoleParamNode)) - { - return false; - } - NonRoleParamNode n = (NonRoleParamNode) o; - return n.canEqual(this) && this.kind.equals(n.kind) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof NonRoleParamNode; - } - - @Override - public int hashCode() - { - int hash = 317; - hash = 31 * super.hashCode(); - return hash; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/simple/OpNode.java b/scribble-core/src/main/java/org/scribble/ast/name/simple/OpNode.java deleted file mode 100644 index 2bdb3047d..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/simple/OpNode.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.type.kind.OpKind; -import org.scribble.type.name.Op; - - -public class OpNode extends SimpleNameNode -{ - public static final String EMPTY_OPERATOR_IDENTIFIER = ""; - - public OpNode(CommonTree source, String identifier) - { - super(source, identifier); - } - - @Override - protected OpNode copy() - { - return new OpNode(this.source, getIdentifier()); - } - - @Override - public OpNode clone(AstFactory af) - { - return (OpNode) af.SimpleNameNode(this.source, OpKind.KIND, getIdentifier()); - } - - @Override - public Op toName() - { - String id = getIdentifier(); - if (id.equals(EMPTY_OPERATOR_IDENTIFIER)) - { - return Op.EMPTY_OPERATOR; - } - return new Op(id); - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof OpNode)) - { - return false; - } - return ((OpNode) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof OpNode; - } - - @Override - public int hashCode() - { - int hash = 347; - hash = 31 * super.hashCode(); - return hash; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/simple/RecVarNode.java b/scribble-core/src/main/java/org/scribble/ast/name/simple/RecVarNode.java deleted file mode 100644 index 4f0283826..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/simple/RecVarNode.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.RecVarKind; -import org.scribble.type.name.RecVar; - -public class RecVarNode extends SimpleNameNode -{ - public RecVarNode(CommonTree source, String identifier) - { - super(source, identifier); - } - - // Factor up to SimpleNameNode? - public RecVarNode reconstruct(String id) - { - ScribDel del = del(); - RecVarNode rv = new RecVarNode(this.source, id); - rv = (RecVarNode) rv.del(del); - return rv; - } - - @Override - protected RecVarNode copy() - { - return new RecVarNode(this.source, getIdentifier()); - } - - @Override - public RecVarNode clone(AstFactory af) - { - return (RecVarNode) af.SimpleNameNode(this.source, RecVarKind.KIND, getIdentifier()); - } - - @Override - public RecVar toName() - { - return new RecVar(getIdentifier()); - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof RecVarNode)) - { - return false; - } - return ((RecVarNode) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof RecVarNode; - } - - @Override - public int hashCode() - { - int hash = 349; - hash = 31 * super.hashCode(); - return hash; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/simple/RoleNode.java b/scribble-core/src/main/java/org/scribble/ast/name/simple/RoleNode.java deleted file mode 100644 index 9f8c65069..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/simple/RoleNode.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.DoArgNode; -import org.scribble.del.ScribDel; -import org.scribble.type.kind.RoleKind; -import org.scribble.type.name.Role; -import org.scribble.visit.Substitutor; - -public class RoleNode extends SimpleNameNode implements DoArgNode //RoleDecl, RoleInstantiation -{ - public RoleNode(CommonTree source, String identifier) - { - super(source, identifier); - } - - @Override - protected RoleNode copy() - { - return new RoleNode(this.source, getIdentifier()); - } - - @Override - public RoleNode clone(AstFactory af) - { - return (RoleNode) af.SimpleNameNode(this.source, RoleKind.KIND, getIdentifier()); - } - - protected RoleNode reconstruct(String identifier) - { - ScribDel del = del(); // Default delegate assigned in ModelFactoryImpl for all simple names - RoleNode rn = new RoleNode(this.source, identifier); - rn = (RoleNode) rn.del(del); - return rn; - } - - @Override - public RoleNode substituteNames(Substitutor subs) - { - // Reconstruct: subprotocolvisitor uses a fullycloned body (and getRoleSubstitution also returns a clone) -- here rename the clone but keep the fresh dels/envs - return reconstruct(subs.getRoleSubstitution(toName()).toName().toString()); - } - - @Override - public Role toName() - { - return new Role(getIdentifier()); - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof RoleNode)) - { - return false; - } - return ((RoleNode) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof RoleNode; - } - - @Override - public int hashCode() - { - int hash = 353; - hash = 31 * super.hashCode(); - return hash; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/simple/ScopeNode.java b/scribble-core/src/main/java/org/scribble/ast/name/simple/ScopeNode.java deleted file mode 100644 index 3423fc362..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/simple/ScopeNode.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.type.kind.ScopeKind; -import org.scribble.type.name.Scope; - -// Currently unused (TODO: interruptible) -public class ScopeNode extends SimpleNameNode -{ - public ScopeNode(CommonTree source, String identifier) - { - super(source, identifier); - } - - @Override - protected ScopeNode copy() - { - return new ScopeNode(this.source, getIdentifier()); - } - - @Override - public ScopeNode clone(AstFactory af) - { - return (ScopeNode) af.SimpleNameNode(this.source, ScopeKind.KIND, getIdentifier()); - } - - @Override - public Scope toName() - { - return new Scope(getIdentifier()); - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof ScopeNode)) - { - return false; - } - return ((ScopeNode) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof ScopeNode; - } - - @Override - public int hashCode() - { - int hash = 359; - hash = 31 * super.hashCode(); - return hash; - } -} diff --git a/scribble-core/src/main/java/org/scribble/ast/name/simple/SimpleNameNode.java b/scribble-core/src/main/java/org/scribble/ast/name/simple/SimpleNameNode.java deleted file mode 100644 index 15438f6c2..000000000 --- a/scribble-core/src/main/java/org/scribble/ast/name/simple/SimpleNameNode.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.tree.CommonTree; -import org.scribble.ast.name.NameNode; -import org.scribble.type.kind.Kind; - -// Parser Identifier -public abstract class SimpleNameNode extends NameNode -{ - public SimpleNameNode(CommonTree source, String identifier) - { - super(source, new String[] { identifier }); - } - - public String getIdentifier() - { - return getLastElement(); - } -} 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/main/Todo.java b/scribble-core/src/main/java/org/scribble/core/job/Todo.java similarity index 99% rename from scribble-core/src/main/java/org/scribble/main/Todo.java rename to scribble-core/src/main/java/org/scribble/core/job/Todo.java index 55a875979..54f105e3d 100644 --- a/scribble-core/src/main/java/org/scribble/main/Todo.java +++ b/scribble-core/src/main/java/org/scribble/core/job/Todo.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.main; +package org.scribble.core.job; // FIXME: project modifiers? 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/model/MPrettyPrint.java b/scribble-core/src/main/java/org/scribble/core/model/MPrettyPrint.java similarity index 86% rename from scribble-core/src/main/java/org/scribble/model/MPrettyPrint.java rename to scribble-core/src/main/java/org/scribble/core/model/MPrettyPrint.java index caf9335f2..d15a1aae1 100644 --- a/scribble-core/src/main/java/org/scribble/model/MPrettyPrint.java +++ b/scribble-core/src/main/java/org/scribble/core/model/MPrettyPrint.java @@ -11,10 +11,10 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.model; +package org.scribble.core.model; public interface MPrettyPrint { String toDot(); - String toAut(); + 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/model/global/actions/SDisconnect.java b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SDisconnect.java similarity index 77% rename from scribble-core/src/main/java/org/scribble/model/global/actions/SDisconnect.java rename to scribble-core/src/main/java/org/scribble/core/model/global/actions/SDisconnect.java index b7cdd3446..7a41d62d6 100644 --- a/scribble-core/src/main/java/org/scribble/model/global/actions/SDisconnect.java +++ b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SDisconnect.java @@ -11,21 +11,21 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.model.global.actions; +package org.scribble.core.model.global.actions; -import org.scribble.type.Payload; -import org.scribble.type.name.Op; -import org.scribble.type.name.Role; +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_OPERATOR, Payload.EMPTY_PAYLOAD); + super(subj, obj, Op.EMPTY_OP, Payload.EMPTY_PAYLOAD); } @Override - public boolean isConnect() + public boolean isRequest() { return true; } @@ -49,11 +49,11 @@ public boolean equals(Object o) { return false; } - return ((SDisconnect) o).canEqual(this) && super.equals(o); + return super.equals(o); // Does canEquals } @Override - public boolean canEqual(Object o) + public boolean canEquals(Object o) { return o instanceof SDisconnect; } 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/model/global/actions/SSend.java b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SSend.java similarity index 75% rename from scribble-core/src/main/java/org/scribble/model/global/actions/SSend.java rename to scribble-core/src/main/java/org/scribble/core/model/global/actions/SSend.java index 40a798055..67117293f 100644 --- a/scribble-core/src/main/java/org/scribble/model/global/actions/SSend.java +++ b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SSend.java @@ -11,17 +11,17 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.model.global.actions; +package org.scribble.core.model.global.actions; -import org.scribble.type.Payload; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; +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, MessageId mid, Payload payload) + public SSend(Role subj, Role obj, MsgId mid, Payload pay) { - super(subj, obj, mid, payload); + super(subj, obj, mid, pay); } @Override @@ -49,11 +49,11 @@ public boolean equals(Object o) { return false; } - return ((SSend) o).canEqual(this) && super.equals(o); + return super.equals(o); // Does canEquals } @Override - public boolean canEqual(Object o) + public boolean canEquals(Object o) { return o instanceof SSend; } 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/type/kind/AmbigKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/AmbigKind.java similarity index 91% rename from scribble-core/src/main/java/org/scribble/type/kind/AmbigKind.java rename to scribble-core/src/main/java/org/scribble/core/type/kind/AmbigKind.java index e5258eceb..0c3b7c6b8 100644 --- a/scribble-core/src/main/java/org/scribble/type/kind/AmbigKind.java +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/AmbigKind.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.kind; +package org.scribble.core.type.kind; public class AmbigKind extends AbstractKind implements NonRoleArgKind//, PayloadTypeKind @@ -20,13 +20,7 @@ public class AmbigKind extends AbstractKind implements NonRoleArgKind//, Payload protected AmbigKind() { - - } - - @Override - public int hashCode() - { - return super.hashCode(); + super("Ambig"); } @Override 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/type/kind/Global.java b/scribble-core/src/main/java/org/scribble/core/type/kind/Global.java similarity index 85% rename from scribble-core/src/main/java/org/scribble/type/kind/Global.java rename to scribble-core/src/main/java/org/scribble/core/type/kind/Global.java index b3c6f5703..c7c6a1d8b 100644 --- a/scribble-core/src/main/java/org/scribble/type/kind/Global.java +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/Global.java @@ -11,21 +11,15 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.kind; +package org.scribble.core.type.kind; -public class Global extends AbstractKind implements ProtocolKind +public class Global extends AbstractKind implements ProtoKind { public static final Global KIND = new Global(); protected Global() { - - } - - @Override - public int hashCode() - { - return super.hashCode(); + super("Global"); } @Override 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/type/kind/ImportKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/ImportKind.java similarity index 94% rename from scribble-core/src/main/java/org/scribble/type/kind/ImportKind.java rename to scribble-core/src/main/java/org/scribble/core/type/kind/ImportKind.java index 7fc3db8c8..6e2eb0d76 100644 --- a/scribble-core/src/main/java/org/scribble/type/kind/ImportKind.java +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/ImportKind.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.kind; +package org.scribble.core.type.kind; public interface ImportKind extends Kind diff --git a/scribble-core/src/main/java/org/scribble/type/kind/Kind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/Kind.java similarity index 91% rename from scribble-core/src/main/java/org/scribble/type/kind/Kind.java rename to scribble-core/src/main/java/org/scribble/core/type/kind/Kind.java index 745d7be4b..134b07bb3 100644 --- a/scribble-core/src/main/java/org/scribble/type/kind/Kind.java +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/Kind.java @@ -11,9 +11,9 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.kind; +package org.scribble.core.type.kind; -import org.scribble.type.name.Name; +import org.scribble.core.type.name.Name; public interface Kind { diff --git a/scribble-core/src/main/java/org/scribble/type/kind/Local.java b/scribble-core/src/main/java/org/scribble/core/type/kind/Local.java similarity index 83% rename from scribble-core/src/main/java/org/scribble/type/kind/Local.java rename to scribble-core/src/main/java/org/scribble/core/type/kind/Local.java index 7f7450692..790c09ca6 100644 --- a/scribble-core/src/main/java/org/scribble/type/kind/Local.java +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/Local.java @@ -11,21 +11,15 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.kind; +package org.scribble.core.type.kind; -public class Local extends AbstractKind implements ProtocolKind, PayloadTypeKind +public class Local extends AbstractKind implements ProtoKind, PayElemKind { public static final Local KIND = new Local(); protected Local() { - - } - - @Override - public int hashCode() - { - return super.hashCode(); + super("Local"); } @Override diff --git a/scribble-core/src/main/java/org/scribble/type/kind/ModuleKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/ModuleKind.java similarity index 91% rename from scribble-core/src/main/java/org/scribble/type/kind/ModuleKind.java rename to scribble-core/src/main/java/org/scribble/core/type/kind/ModuleKind.java index 2d6391757..65a392347 100644 --- a/scribble-core/src/main/java/org/scribble/type/kind/ModuleKind.java +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/ModuleKind.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.kind; +package org.scribble.core.type.kind; public class ModuleKind extends AbstractKind implements ImportKind { @@ -19,13 +19,7 @@ public class ModuleKind extends AbstractKind implements ImportKind protected ModuleKind() { - - } - - @Override - public int hashCode() - { - return super.hashCode(); + super("Module"); } @Override diff --git a/scribble-core/src/main/java/org/scribble/type/kind/ModuleMemberKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/ModuleMemberKind.java similarity index 94% rename from scribble-core/src/main/java/org/scribble/type/kind/ModuleMemberKind.java rename to scribble-core/src/main/java/org/scribble/core/type/kind/ModuleMemberKind.java index 0182baaa1..c180acb15 100644 --- a/scribble-core/src/main/java/org/scribble/type/kind/ModuleMemberKind.java +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/ModuleMemberKind.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.kind; +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/type/kind/NonRoleArgKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/NonRoleArgKind.java similarity index 80% rename from scribble-core/src/main/java/org/scribble/type/kind/NonRoleArgKind.java rename to scribble-core/src/main/java/org/scribble/core/type/kind/NonRoleArgKind.java index 9ad41aa55..fc9d53735 100644 --- a/scribble-core/src/main/java/org/scribble/type/kind/NonRoleArgKind.java +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/NonRoleArgKind.java @@ -11,12 +11,12 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.kind; +package org.scribble.core.type.kind; // Following sesstype.Arg hierarchy -// Non-role args -- includes AmbigKind (cf. AntlrNonRoleArgList) -public interface NonRoleArgKind extends NonProtocolKind +// Non-role args -- includes NonRoleParamKind, and AmbigKind +public interface NonRoleArgKind extends NonProtoKind { } diff --git a/scribble-core/src/main/java/org/scribble/type/kind/NonRoleParamKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/NonRoleParamKind.java similarity index 94% rename from scribble-core/src/main/java/org/scribble/type/kind/NonRoleParamKind.java rename to scribble-core/src/main/java/org/scribble/core/type/kind/NonRoleParamKind.java index d69912eb4..9eb8768e2 100644 --- a/scribble-core/src/main/java/org/scribble/type/kind/NonRoleParamKind.java +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/NonRoleParamKind.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.kind; +package org.scribble.core.type.kind; // Non-role params 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/type/kind/PackageKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/PackageKind.java similarity index 91% rename from scribble-core/src/main/java/org/scribble/type/kind/PackageKind.java rename to scribble-core/src/main/java/org/scribble/core/type/kind/PackageKind.java index eabd07294..ff060c378 100644 --- a/scribble-core/src/main/java/org/scribble/type/kind/PackageKind.java +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/PackageKind.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.kind; +package org.scribble.core.type.kind; public class PackageKind extends AbstractKind { @@ -19,13 +19,7 @@ public class PackageKind extends AbstractKind protected PackageKind() { - - } - - @Override - public int hashCode() - { - return super.hashCode(); + super("Package"); } @Override diff --git a/scribble-core/src/main/java/org/scribble/type/kind/ParamKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/ParamKind.java similarity index 94% rename from scribble-core/src/main/java/org/scribble/type/kind/ParamKind.java rename to scribble-core/src/main/java/org/scribble/core/type/kind/ParamKind.java index 998f2388c..1d99e9172 100644 --- a/scribble-core/src/main/java/org/scribble/type/kind/ParamKind.java +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/ParamKind.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.kind; +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/type/kind/RecVarKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/RecVarKind.java similarity index 90% rename from scribble-core/src/main/java/org/scribble/type/kind/RecVarKind.java rename to scribble-core/src/main/java/org/scribble/core/type/kind/RecVarKind.java index b7e9c9ebd..073498914 100644 --- a/scribble-core/src/main/java/org/scribble/type/kind/RecVarKind.java +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/RecVarKind.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.kind; +package org.scribble.core.type.kind; public class RecVarKind extends AbstractKind { @@ -19,13 +19,7 @@ public class RecVarKind extends AbstractKind protected RecVarKind() { - - } - - @Override - public int hashCode() - { - return super.hashCode(); + super("RecVar"); } @Override diff --git a/scribble-core/src/main/java/org/scribble/type/kind/RoleKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/RoleKind.java similarity index 91% rename from scribble-core/src/main/java/org/scribble/type/kind/RoleKind.java rename to scribble-core/src/main/java/org/scribble/core/type/kind/RoleKind.java index 2325077b0..8fd3d4e96 100644 --- a/scribble-core/src/main/java/org/scribble/type/kind/RoleKind.java +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/RoleKind.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.kind; +package org.scribble.core.type.kind; public class RoleKind extends AbstractKind implements ParamKind { @@ -19,13 +19,7 @@ public class RoleKind extends AbstractKind implements ParamKind protected RoleKind() { - - } - - @Override - public int hashCode() - { - return super.hashCode(); + super("Role"); } @Override diff --git a/scribble-core/src/main/java/org/scribble/type/kind/SigKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/SigKind.java similarity index 88% rename from scribble-core/src/main/java/org/scribble/type/kind/SigKind.java rename to scribble-core/src/main/java/org/scribble/core/type/kind/SigKind.java index b485b061a..02545144e 100644 --- a/scribble-core/src/main/java/org/scribble/type/kind/SigKind.java +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/SigKind.java @@ -11,24 +11,18 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.kind; +package org.scribble.core.type.kind; // Following sesstype.Arg hierarchy -public class SigKind extends AbstractKind implements NonRoleParamKind, MessageIdKind, //ArgKind +public class SigKind extends AbstractKind implements NonRoleParamKind, MsgIdKind, //ArgKind ModuleMemberKind { public static final SigKind KIND = new SigKind(); protected SigKind() { - - } - - @Override - public int hashCode() - { - return super.hashCode(); + super("Sig"); } @Override diff --git a/scribble-core/src/main/java/org/scribble/type/name/AbstractName.java b/scribble-core/src/main/java/org/scribble/core/type/name/AbstractName.java similarity index 81% rename from scribble-core/src/main/java/org/scribble/type/name/AbstractName.java rename to scribble-core/src/main/java/org/scribble/core/type/name/AbstractName.java index 12d2ca2ec..91964724d 100644 --- a/scribble-core/src/main/java/org/scribble/type/name/AbstractName.java +++ b/scribble-core/src/main/java/org/scribble/core/type/name/AbstractName.java @@ -11,20 +11,20 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.name; +package org.scribble.core.type.name; import java.io.IOException; import java.util.Arrays; -import org.scribble.type.kind.Kind; +import org.scribble.core.type.kind.Kind; public abstract class AbstractName implements Name { private static final long serialVersionUID = 1L; - private K kind; // non-final for serialization + protected K kind; // non-final for serialization - private String[] elems; + protected String[] elems; protected AbstractName(K kind, String... elems) { @@ -50,22 +50,11 @@ public boolean isEmpty() return this.elems.length == 0; } - @Override - public boolean isPrefixed() - { - return this.elems.length > 1; - } - @Override public String[] getElements() { return Arrays.copyOf(this.elems, this.elems.length); } - @Override - public String[] getPrefixElements() - { - return Arrays.copyOfRange(this.elems, 0, this.elems.length - 1); - } // Not SimpleName so that e.g. ModuleName can return a simple ModuleName @Override @@ -85,11 +74,12 @@ public boolean equals(Object o) { return false; } - AbstractName n = (AbstractName) o; - return n.canEqual(this) && this.kind.equals(n.kind) && Arrays.equals(this.elems, (n.elems)); + AbstractName them = (AbstractName) o; + return them.canEquals(this) && this.kind.equals(them.kind) + && Arrays.equals(this.elems, them.elems); } - public abstract boolean canEqual(Object o); + public abstract boolean canEquals(Object o); @Override public int hashCode() diff --git a/scribble-core/src/main/java/org/scribble/type/name/AmbigName.java b/scribble-core/src/main/java/org/scribble/core/type/name/AmbigName.java similarity index 76% rename from scribble-core/src/main/java/org/scribble/type/name/AmbigName.java rename to scribble-core/src/main/java/org/scribble/core/type/name/AmbigName.java index 7e71c4b2d..e8c0f8274 100644 --- a/scribble-core/src/main/java/org/scribble/type/name/AmbigName.java +++ b/scribble-core/src/main/java/org/scribble/core/type/name/AmbigName.java @@ -11,9 +11,9 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.name; +package org.scribble.core.type.name; -import org.scribble.type.kind.AmbigKind; +import org.scribble.core.type.kind.AmbigKind; public class AmbigName extends AbstractName { @@ -24,14 +24,14 @@ public AmbigName(String text) super(AmbigKind.KIND, text); } - public MessageSigName toMessageSigName() + public SigName toSigName() { - return new MessageSigName(getLastElement()); + return new SigName(getLastElement()); } - public DataType toDataType() + public DataName toDataName() { - return new DataType(getLastElement()); + return new DataName(getLastElement()); } @Override @@ -46,10 +46,10 @@ public boolean equals(Object o) return false; } AmbigName n = (AmbigName) o; - return n.canEqual(this) && super.equals(o); + return n.canEquals(this) && super.equals(o); } - public boolean canEqual(Object o) + public boolean canEquals(Object o) { return o instanceof AmbigName; } @@ -57,7 +57,7 @@ public boolean canEqual(Object o) @Override public int hashCode() { - int hash = 2753; + 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/type/name/MemberName.java b/scribble-core/src/main/java/org/scribble/core/type/name/MemberName.java similarity index 88% rename from scribble-core/src/main/java/org/scribble/type/name/MemberName.java rename to scribble-core/src/main/java/org/scribble/core/type/name/MemberName.java index c5f39f80c..4b2c240f9 100644 --- a/scribble-core/src/main/java/org/scribble/type/name/MemberName.java +++ b/scribble-core/src/main/java/org/scribble/core/type/name/MemberName.java @@ -11,13 +11,13 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.name; +package org.scribble.core.type.name; -import org.scribble.type.kind.Kind; +import org.scribble.core.type.kind.Kind; // Simple name or qualified name -public abstract class MemberName extends QualifiedName +public abstract class MemberName extends QualName { private static final long serialVersionUID = 1L; @@ -31,6 +31,7 @@ public MemberName(K kind, String simplename) super(kind, Name.compileElements(ModuleName.EMPTY_MODULENAME.getElements(), simplename)); } + @Override public ModuleName getPrefix() { return new ModuleName(getPrefixElements()); diff --git a/scribble-core/src/main/java/org/scribble/type/name/ModuleName.java b/scribble-core/src/main/java/org/scribble/core/type/name/ModuleName.java similarity index 89% rename from scribble-core/src/main/java/org/scribble/type/name/ModuleName.java rename to scribble-core/src/main/java/org/scribble/core/type/name/ModuleName.java index d250feea3..4511bde8d 100644 --- a/scribble-core/src/main/java/org/scribble/type/name/ModuleName.java +++ b/scribble-core/src/main/java/org/scribble/core/type/name/ModuleName.java @@ -11,16 +11,16 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.name; +package org.scribble.core.type.name; import java.nio.file.Path; import java.nio.file.Paths; -import org.scribble.ast.Constants; -import org.scribble.type.kind.ModuleKind; +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 QualifiedName +public class ModuleName extends QualName { private static final long serialVersionUID = 1L; @@ -90,10 +90,10 @@ public boolean equals(Object o) return false; } ModuleName n = (ModuleName) o; - return n.canEqual(this) && super.equals(o); + return n.canEquals(this) && super.equals(o); } - public boolean canEqual(Object o) + public boolean canEquals(Object o) { return o instanceof ModuleName; } 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/type/name/Name.java b/scribble-core/src/main/java/org/scribble/core/type/name/Name.java similarity index 76% rename from scribble-core/src/main/java/org/scribble/type/name/Name.java rename to scribble-core/src/main/java/org/scribble/core/type/name/Name.java index 96a4295a6..2c103444a 100644 --- a/scribble-core/src/main/java/org/scribble/type/name/Name.java +++ b/scribble-core/src/main/java/org/scribble/core/type/name/Name.java @@ -11,25 +11,24 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.name; +package org.scribble.core.type.name; import java.io.Serializable; import java.util.Arrays; -import org.scribble.type.kind.Kind; +import org.scribble.core.type.kind.Kind; public interface Name extends Serializable { - public K getKind(); + K getKind(); - public int getElementCount(); - public boolean isEmpty(); - public boolean isPrefixed(); - - public String[] getElements(); - public String[] getPrefixElements(); - public String getLastElement(); + String[] getElements(); + int getElementCount(); + boolean isEmpty(); + String getLastElement(); + //boolean isPrefixed(); + //String[] getPrefixElements(); static String[] compileElements(String[] cn, String n) { diff --git a/scribble-core/src/main/java/org/scribble/type/name/Named.java b/scribble-core/src/main/java/org/scribble/core/type/name/Named.java similarity index 89% rename from scribble-core/src/main/java/org/scribble/type/name/Named.java rename to scribble-core/src/main/java/org/scribble/core/type/name/Named.java index 227157515..9d5043321 100644 --- a/scribble-core/src/main/java/org/scribble/type/name/Named.java +++ b/scribble-core/src/main/java/org/scribble/core/type/name/Named.java @@ -11,9 +11,9 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.name; +package org.scribble.core.type.name; -import org.scribble.type.kind.Kind; +import org.scribble.core.type.kind.Kind; public interface Named diff --git a/scribble-core/src/main/java/org/scribble/type/name/Op.java b/scribble-core/src/main/java/org/scribble/core/type/name/Op.java similarity index 80% rename from scribble-core/src/main/java/org/scribble/type/name/Op.java rename to scribble-core/src/main/java/org/scribble/core/type/name/Op.java index 56720b373..27bab91db 100644 --- a/scribble-core/src/main/java/org/scribble/type/name/Op.java +++ b/scribble-core/src/main/java/org/scribble/core/type/name/Op.java @@ -11,15 +11,15 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.name; +package org.scribble.core.type.name; -import org.scribble.type.kind.OpKind; +import org.scribble.core.type.kind.OpKind; -public class Op extends AbstractName implements MessageId +public class Op extends AbstractName implements MsgId { private static final long serialVersionUID = 1L; - public static final Op EMPTY_OPERATOR = new Op(); + public static final Op EMPTY_OP = new Op(); protected Op() { @@ -49,10 +49,10 @@ public boolean equals(Object o) return false; } Op n = (Op) o; - return n.canEqual(this) && super.equals(o); + return n.canEquals(this) && super.equals(o); } - public boolean canEqual(Object o) + public boolean canEquals(Object o) { return o instanceof Op; } diff --git a/scribble-core/src/main/java/org/scribble/type/name/PackageName.java b/scribble-core/src/main/java/org/scribble/core/type/name/PackageName.java similarity index 85% rename from scribble-core/src/main/java/org/scribble/type/name/PackageName.java rename to scribble-core/src/main/java/org/scribble/core/type/name/PackageName.java index 843c1f6c5..96bc5a77d 100644 --- a/scribble-core/src/main/java/org/scribble/type/name/PackageName.java +++ b/scribble-core/src/main/java/org/scribble/core/type/name/PackageName.java @@ -11,11 +11,11 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.name; +package org.scribble.core.type.name; -import org.scribble.type.kind.PackageKind; +import org.scribble.core.type.kind.PackageKind; -public class PackageName extends QualifiedName +public class PackageName extends QualName { private static final long serialVersionUID = 1L; @@ -50,10 +50,10 @@ public boolean equals(Object o) return false; } PackageName n = (PackageName) o; - return n.canEqual(this) && super.equals(o); + return n.canEquals(this) && super.equals(o); } - public boolean canEqual(Object o) + public boolean canEquals(Object o) { return o instanceof PackageName; } 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/type/name/RecVar.java b/scribble-core/src/main/java/org/scribble/core/type/name/RecVar.java similarity index 83% rename from scribble-core/src/main/java/org/scribble/type/name/RecVar.java rename to scribble-core/src/main/java/org/scribble/core/type/name/RecVar.java index b69f8cde7..7cdbc56ce 100644 --- a/scribble-core/src/main/java/org/scribble/type/name/RecVar.java +++ b/scribble-core/src/main/java/org/scribble/core/type/name/RecVar.java @@ -11,10 +11,11 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.name; +package org.scribble.core.type.name; -import org.scribble.type.kind.RecVarKind; +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; @@ -41,10 +42,10 @@ public boolean equals(Object o) return false; } RecVar n = (RecVar) o; - return n.canEqual(this) && super.equals(o); + return n.canEquals(this) && super.equals(o); } - public boolean canEqual(Object o) + public boolean canEquals(Object o) { return o instanceof RecVar; } diff --git a/scribble-core/src/main/java/org/scribble/type/name/Role.java b/scribble-core/src/main/java/org/scribble/core/type/name/Role.java similarity index 76% rename from scribble-core/src/main/java/org/scribble/type/name/Role.java rename to scribble-core/src/main/java/org/scribble/core/type/name/Role.java index fa537fa51..fb0e96349 100644 --- a/scribble-core/src/main/java/org/scribble/type/name/Role.java +++ b/scribble-core/src/main/java/org/scribble/core/type/name/Role.java @@ -11,14 +11,15 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type.name; +package org.scribble.core.type.name; -import org.scribble.type.kind.RoleKind; +import org.scribble.core.type.kind.RoleKind; -public class Role extends AbstractName +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; @@ -44,10 +45,10 @@ public boolean equals(Object o) return false; } Role n = (Role) o; - return n.canEqual(this) && super.equals(o); + return n.canEquals(this) && super.equals(o); } - public boolean canEqual(Object o) + public boolean canEquals(Object o) { return o instanceof Role; } 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/type/Arg.java b/scribble-core/src/main/java/org/scribble/core/type/session/Arg.java similarity index 89% rename from scribble-core/src/main/java/org/scribble/type/Arg.java rename to scribble-core/src/main/java/org/scribble/core/type/session/Arg.java index 5c1a63b8e..74b2999bd 100644 --- a/scribble-core/src/main/java/org/scribble/type/Arg.java +++ b/scribble-core/src/main/java/org/scribble/core/type/session/Arg.java @@ -11,9 +11,9 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.type; +package org.scribble.core.type.session; -import org.scribble.type.kind.NonRoleArgKind; +import org.scribble.core.type.kind.NonRoleArgKind; // A subprotocol argument (DoArgNode): SigKind or PayloadTypeKind public interface Arg 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/del/ChoiceDel.java b/scribble-core/src/main/java/org/scribble/del/ChoiceDel.java deleted file mode 100644 index d148fc4b4..000000000 --- a/scribble-core/src/main/java/org/scribble/del/ChoiceDel.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Choice; -import org.scribble.ast.ScribNode; -import org.scribble.main.ScribbleException; -import org.scribble.visit.InlinedProtocolUnfolder; -import org.scribble.visit.env.UnfoldingEnv; -import org.scribble.visit.wf.ExplicitCorrelationChecker; -import org.scribble.visit.wf.env.ExplicitCorrelationEnv; - -public abstract class ChoiceDel extends CompoundInteractionNodeDel -{ - public ChoiceDel() - { - - } - - @Override - public void enterInlinedProtocolUnfolding(ScribNode parent, ScribNode child, InlinedProtocolUnfolder unf) throws ScribbleException - { - UnfoldingEnv env = unf.peekEnv().enterContext(); - env = env.pushChoiceParent(); // Above is already a copy, but fine - unf.pushEnv(env); - } - - @Override - public Choice leaveInlinedProtocolUnfolding(ScribNode parent, ScribNode child, InlinedProtocolUnfolder unf, ScribNode visited) throws ScribbleException - { - Choice cho = (Choice) visited; - List benvs = - cho.getBlocks().stream().map((b) -> (UnfoldingEnv) b.del().env()).collect(Collectors.toList()); - UnfoldingEnv merged = unf.popEnv().mergeContexts(benvs); - unf.pushEnv(merged); - return (Choice) super.leaveInlinedProtocolUnfolding(parent, child, unf, visited); // Done merge of children here, super does merge into parent - } - - @Override - public void enterExplicitCorrelationCheck(ScribNode parent, ScribNode child, ExplicitCorrelationChecker checker) throws ScribbleException - { - ExplicitCorrelationEnv env = checker.peekEnv().enterContext(); - checker.pushEnv(env); - } - - @Override - public Choice leaveExplicitCorrelationCheck(ScribNode parent, ScribNode child, ExplicitCorrelationChecker checker, ScribNode visited) throws ScribbleException - { - Choice cho = (Choice) visited; - List benvs = - cho.getBlocks().stream().map((b) -> (ExplicitCorrelationEnv) b.del().env()).collect(Collectors.toList()); - ExplicitCorrelationEnv merged = checker.popEnv().mergeContexts(benvs); - checker.pushEnv(merged); - return (Choice) super.leaveExplicitCorrelationCheck(parent, child, checker, visited); // Done merge of children here, super does merge into parent - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/CompoundInteractionDel.java b/scribble-core/src/main/java/org/scribble/del/CompoundInteractionDel.java deleted file mode 100644 index 53f42e34e..000000000 --- a/scribble-core/src/main/java/org/scribble/del/CompoundInteractionDel.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.main.ScribbleException; -import org.scribble.visit.InlinedProtocolUnfolder; -import org.scribble.visit.context.UnguardedChoiceDoProjectionChecker; -import org.scribble.visit.wf.ExplicitCorrelationChecker; -import org.scribble.visit.wf.WFChoiceChecker; - -// For CompoundInteractionNode and ProtocolBlock -public abstract class CompoundInteractionDel extends ScribDelBase -{ - public CompoundInteractionDel() - { - - } - - // Should only do for projections, but OK here (visitor only run on projections) - @Override - public void enterUnguardedChoiceDoProjectionCheck(ScribNode parent, ScribNode child, UnguardedChoiceDoProjectionChecker checker) throws ScribbleException - { - ScribDelBase.pushVisitorEnv(this, checker); - } - - // Should only do for projections, but OK here (visitor only run on projections) - @Override - public ScribNode leaveUnguardedChoiceDoProjectionCheck(ScribNode parent, ScribNode child, UnguardedChoiceDoProjectionChecker checker, ScribNode visited) throws ScribbleException - { - // Overridden in CompoundInteractionNodeDel to do merging of child context into parent context - return ScribDelBase.popAndSetVisitorEnv(this, checker, visited); - } - - @Override - public void enterInlinedProtocolUnfolding(ScribNode parent, ScribNode child, InlinedProtocolUnfolder unf) throws ScribbleException - { - ScribDelBase.pushVisitorEnv(this, unf); - } - - @Override - public ScribNode leaveInlinedProtocolUnfolding(ScribNode parent, ScribNode child, InlinedProtocolUnfolder unf, ScribNode visited) throws ScribbleException - { - // Overridden in CompoundInteractionNodeDel to do merging of child context into parent context - return ScribDelBase.popAndSetVisitorEnv(this, unf, visited); - } - - @Override - public void enterInlinedWFChoiceCheck(ScribNode parent, ScribNode child, WFChoiceChecker checker) throws ScribbleException - { - ScribDelBase.pushVisitorEnv(this, checker); - } - - @Override - public ScribNode leaveInlinedWFChoiceCheck(ScribNode parent, ScribNode child, WFChoiceChecker checker, ScribNode visited) throws ScribbleException - { - // Overridden in CompoundInteractionNodeDel to do merging of child context into parent context - return ScribDelBase.popAndSetVisitorEnv(this, checker, visited); - } - - @Override - public void enterExplicitCorrelationCheck(ScribNode parent, ScribNode child, ExplicitCorrelationChecker checker) throws ScribbleException - { - ScribDelBase.pushVisitorEnv(this, checker); - } - - @Override - public ScribNode leaveExplicitCorrelationCheck(ScribNode parent, ScribNode child, ExplicitCorrelationChecker checker, ScribNode visited) throws ScribbleException - { - // Overridden in CompoundInteractionNodeDel to do merging of child context into parent context - return ScribDelBase.popAndSetVisitorEnv(this, checker, visited); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/CompoundInteractionNodeDel.java b/scribble-core/src/main/java/org/scribble/del/CompoundInteractionNodeDel.java deleted file mode 100644 index 70035ebbb..000000000 --- a/scribble-core/src/main/java/org/scribble/del/CompoundInteractionNodeDel.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.CompoundInteractionNode; -import org.scribble.ast.ScribNode; -import org.scribble.main.ScribbleException; -import org.scribble.visit.InlinedProtocolUnfolder; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.UnguardedChoiceDoProjectionChecker; -import org.scribble.visit.context.env.UnguardedChoiceDoEnv; -import org.scribble.visit.env.UnfoldingEnv; -import org.scribble.visit.wf.ExplicitCorrelationChecker; -import org.scribble.visit.wf.WFChoiceChecker; -import org.scribble.visit.wf.env.ExplicitCorrelationEnv; -import org.scribble.visit.wf.env.WFChoiceEnv; - -public abstract class CompoundInteractionNodeDel extends CompoundInteractionDel implements InteractionNodeDel -{ - public CompoundInteractionNodeDel() - { - - } - - @Override - public void enterProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl) throws ScribbleException - { - ScribDelBase.pushVisitorEnv(this, inl); - } - - @Override - public ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - return ScribDelBase.popAndSetVisitorEnv(this, inl, visited); - } - - // In the following only leaves are overridden to do additional merging -- enters remain as for super by default - // Specialised enters will be overridden per node (e.g., GChoiceDel.enterInlinedWFChoiceCheck) -- corresponding leaves will use their super (i.e., the below) to do merging - - // Should only do for projections, but OK here (visitor only run on projections) - @Override - public ScribNode leaveUnguardedChoiceDoProjectionCheck(ScribNode parent, ScribNode child, UnguardedChoiceDoProjectionChecker checker, ScribNode visited) throws ScribbleException - { - // Override super routine (in CompoundInteractionDel, which just does base popAndSet) to do merging of child context into parent context - UnguardedChoiceDoEnv visited_env = checker.popEnv(); // popAndSet current - setEnv(visited_env); - UnguardedChoiceDoEnv parent_env = checker.popEnv(); // pop-merge-push parent - parent_env = parent_env.mergeContext(visited_env); - checker.pushEnv(parent_env); - return (CompoundInteractionNode) visited; - } - - @Override - public ScribNode leaveInlinedProtocolUnfolding(ScribNode parent, ScribNode child, InlinedProtocolUnfolder unf, ScribNode visited) throws ScribbleException - { - // Override super routine (in CompoundInteractionDel, which just does base popAndSet) to do merging of child context into parent context - // Need to further override for "compound" nodes with block children, e.g., Choice/RecursionDel, to merge children together and then into current (then call here via super to set and merge current into parent) - UnfoldingEnv visited_env = unf.popEnv(); // popAndSet current - setEnv(visited_env); - UnfoldingEnv parent_env = unf.popEnv(); // pop-merge-push parent - parent_env = parent_env.mergeContext(visited_env); - unf.pushEnv(parent_env); - return (CompoundInteractionNode) visited; - } - - @Override - public CompoundInteractionNode leaveInlinedWFChoiceCheck(ScribNode parent, ScribNode child, WFChoiceChecker checker, ScribNode visited) throws ScribbleException - { - WFChoiceEnv visited_env = checker.popEnv(); // popAndSet current - setEnv(visited_env); - WFChoiceEnv parent_env = checker.popEnv(); // pop-merge-push parent - parent_env = parent_env.mergeContext(visited_env); - checker.pushEnv(parent_env); - return (CompoundInteractionNode) visited; - } - - @Override - public ScribNode leaveExplicitCorrelationCheck(ScribNode parent, ScribNode child, ExplicitCorrelationChecker checker, ScribNode visited) throws ScribbleException - { - // Override super routine (in CompoundInteractionDel, which just does base popAndSet) to do merging of child context into parent context - // Need to further override for "multi-compound" nodes, e.g., ChoiceDel - ExplicitCorrelationEnv visited_env = checker.popEnv(); // popAndSet current - setEnv(visited_env); - ExplicitCorrelationEnv parent_env = checker.popEnv(); // pop-merge-push parent - parent_env = parent_env.mergeContext(visited_env); - checker.pushEnv(parent_env); - return (CompoundInteractionNode) visited; - } - - /*@Override - public void enterWFChoicePathCheck(ScribNode parent, ScribNode child, WFChoicePathChecker coll) throws ScribbleException - { - WFChoicePathEnv env = coll.peekEnv().enterContext(); - env = env.clear(); - coll.pushEnv(env); - }*/ - - /*@Override - public CompoundInteractionNode leaveWFChoicePathCheck(ScribNode parent, ScribNode child, WFChoicePathChecker coll, ScribNode visited) throws ScribbleException - //public CompoundInteractionNode leavePathCollection(ScribNode parent, ScribNode child, PathCollectionVisitor coll, ScribNode visited) throws ScribbleException - { - WFChoicePathEnv visited_env = coll.popEnv(); // popAndSet current - setEnv(visited_env); - WFChoicePathEnv parent_env = coll.popEnv(); // pop-merge-push parent - parent_env = parent_env.mergeContext(visited_env); - coll.pushEnv(parent_env); - - /*System.out.println("3: " + parent_env.getPaths().size()); - System.out.println("4: " + parent_env.getPaths() + ""); - System.out.println("4: " + visited + "\n");* / - - return (CompoundInteractionNode) visited; - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/del/ConnectionActionDel.java b/scribble-core/src/main/java/org/scribble/del/ConnectionActionDel.java deleted file mode 100644 index 18ebbff86..000000000 --- a/scribble-core/src/main/java/org/scribble/del/ConnectionActionDel.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ConnectionAction; -import org.scribble.ast.ScribNode; -import org.scribble.main.ScribbleException; -import org.scribble.visit.InlinedProtocolUnfolder; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.env.UnfoldingEnv; -import org.scribble.visit.util.RoleCollector; - -// FIXME: factor with MessageTransferDel -public abstract class ConnectionActionDel extends SimpleInteractionNodeDel -{ - public ConnectionActionDel() - { - - } - - @Override - public ConnectionAction leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - ConnectionAction c = (ConnectionAction) visited; - ConnectionAction inlined = (ConnectionAction) c.clone(inl.job.af); - inl.pushEnv(inl.popEnv().setTranslation(inlined)); - return (ConnectionAction) super.leaveProtocolInlining(parent, child, inl, c); - } - - /*@Override - public void enterChoiceUnguardedSubprotocolCheck(ScribNode parent, ScribNode child, ChoiceUnguardedSubprotocolChecker checker) throws ScribbleException - { - ChoiceUnguardedSubprotocolEnv env = checker.popEnv(); - env = env.disablePrune(); - checker.pushEnv(env); - }*/ - - @Override - public void enterInlinedProtocolUnfolding(ScribNode parent, ScribNode child, InlinedProtocolUnfolder unf) throws ScribbleException - { - UnfoldingEnv env = unf.popEnv(); - env = env.disableUnfold(); - unf.pushEnv(env); - } - - @Override - public ScribNode leaveRoleCollection(ScribNode parent, ScribNode child, RoleCollector coll, ScribNode visited) - { - ConnectionAction c = (ConnectionAction) visited; - coll.addName(c.src.toName()); - coll.addName(c.dest.toName()); - return visited; - } - - /*@Override - public ScribNode leaveMessageIdCollection(ScribNode parent, ScribNode child, MessageIdCollector coll, ScribNode visited) - { - Connect c = (Connect) visited; - if (c.msg.isMessageSigNode() || c.msg.isMessageSigNameNode()) - { - coll.addName((MessageId) c.msg.toMessage().getId()); - } - else - { - throw new RuntimeException("Shouldn't get in here: " + c.msg); - } - return visited; - }*/ - - /*@Override - public ScribNode leaveEnablingMessageCollection(ScribNode parent, ScribNode child, EnablingMessageCollector coll, ScribNode visited) - { - Connect mt = (Connect) visited; - coll.addEnabling(mt.src.toName(), mt.getDestinations().get(0).toName(), mt.msg.toMessage().getId()); // FIXME: multicast - return visited; - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/del/ContinueDel.java b/scribble-core/src/main/java/org/scribble/del/ContinueDel.java deleted file mode 100644 index 410a31836..000000000 --- a/scribble-core/src/main/java/org/scribble/del/ContinueDel.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Continue; -import org.scribble.ast.Recursion; -import org.scribble.ast.ScribNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.RecVar; -import org.scribble.visit.InlinedProtocolUnfolder; -import org.scribble.visit.util.RecVarCollector; - -public abstract class ContinueDel extends SimpleInteractionNodeDel -{ - public ContinueDel() - { - - } - - /*@Override - public Continue leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - Continue c = (Continue) visited; - Continue inlined = (Continue) c.clone(); - inl.pushEnv(inl.popEnv().setTranslation(inlined)); - return (Continue) super.leaveProtocolInlining(parent, child, inl, c); - }*/ - - @Override - public ScribNode leaveInlinedProtocolUnfolding(ScribNode parent, ScribNode child, InlinedProtocolUnfolder unf, ScribNode visited) throws ScribbleException - { - Continue cont = (Continue) visited; - RecVar rv = cont.recvar.toName(); - if (unf.isContinueUnguarded(rv)) // Without this, graph building becomes sensitive to the order of choice blocks (specifically, the relative position were the side effect (re-set entry to rec state) of an unguarded continue is performed) - { - Recursion tmp = unf.getRecVar(rv); - if (tmp == null) // Hacky? for recursive unfolding of cached blocks - { - return cont; - } - return unf.getRecVar(rv).clone(unf.job.af); - } - else if (unf.shouldUnfoldForUnguardedRec(rv)) - { - return unf.getRecVar(rv).clone(unf.job.af); - } - return cont; - } - - @Override - public ScribNode leaveRecVarCollection(ScribNode parent, ScribNode child, RecVarCollector coll, ScribNode visited) - throws ScribbleException - { - coll.removeName(((Continue) visited).recvar.toName()); - return visited; - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/DoArgListDel.java b/scribble-core/src/main/java/org/scribble/del/DoArgListDel.java deleted file mode 100644 index c0b2d9b1b..000000000 --- a/scribble-core/src/main/java/org/scribble/del/DoArgListDel.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Do; -import org.scribble.ast.DoArgList; -import org.scribble.ast.HeaderParamDeclList; -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ModuleContext; -import org.scribble.main.JobContext; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.ProtocolName; -import org.scribble.visit.wf.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 parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - DoArgList dal = (DoArgList) visited; - List args = dal.getDoArgs(); - ProtocolDecl pd = getTargetProtocolDecl((Do) parent, disamb); - if (args.size() != getParamDeclList(pd).getDecls().size()) - { - throw new ScribbleException(visited.getSource(), "Do arity mismatch for " + pd.header + ": " + 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 ProtocolDecl getTargetProtocolDecl(Do parent, NameDisambiguator disamb) throws ScribbleException - { - ModuleContext mc = disamb.getModuleContext(); - JobContext jc = disamb.job.getContext(); - Do doo = (Do) parent; - ProtocolName pn = doo.proto.toName(); - /*if (!mc.isVisibleProtocolDeclName(simpname)) // FIXME: should be checked somewhere else? earlier (do-entry?) -- done - { - throw new ScribbleException("Protocol decl not visible: " + simpname); - }*/ - ProtocolName fullname = mc.getVisibleProtocolDeclFullName(pn); // Lookup in visible names -- not deps, because do target name not disambiguated yet (will be done later this pass) - return jc.getModule(fullname.getPrefix()).getProtocolDecl(pn.getSimpleName()); - } - - protected abstract HeaderParamDeclList getParamDeclList(ProtocolDecl pd); -} diff --git a/scribble-core/src/main/java/org/scribble/del/DoDel.java b/scribble-core/src/main/java/org/scribble/del/DoDel.java deleted file mode 100644 index ffb3ffe8c..000000000 --- a/scribble-core/src/main/java/org/scribble/del/DoDel.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Do; -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ModuleContext; -import org.scribble.ast.name.qualified.ProtocolNameNode; -import org.scribble.main.JobContext; -import org.scribble.main.ScribbleException; -import org.scribble.type.SubprotocolSig; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.ProtocolName; -import org.scribble.type.name.Role; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.ProtocolDeclContextBuilder; -import org.scribble.visit.wf.NameDisambiguator; - -public abstract class DoDel extends SimpleInteractionNodeDel -{ - public DoDel() - { - - } - - @Override - public void enterDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb) throws ScribbleException - { - ModuleContext mc = disamb.getModuleContext(); - Do doo = (Do) child; - ProtocolName simpname = doo.proto.toName(); - if (!mc.isVisibleProtocolDeclName(simpname)) // FIXME: do on entry here, before visiting DoArgListDel - { - throw new ScribbleException(doo.proto.getSource(), "Protocol decl not visible: " + simpname); - } - } - - @Override - public ScribNode leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - return leaveDisambiguationAux(parent, child, disamb, visited); // 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(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) - throws ScribbleException - { - @SuppressWarnings("unchecked") // Doesn't matter what K is, just need to propagate it down - Do doo = (Do) visited; - ModuleContext mc = disamb.getModuleContext(); - ProtocolName fullname = mc.getVisibleProtocolDeclFullName(doo.proto.toName()); - ProtocolNameNode pnn = (ProtocolNameNode) - disamb.job.af.QualifiedNameNode(doo.proto.getSource(), fullname.getKind(), fullname.getElements()); - // Didn't keep original namenode del - return doo.reconstruct(doo.roles, doo.args, pnn); - } - - @Override - public Do leaveProtocolDeclContextBuilding(ScribNode parent, ScribNode child, ProtocolDeclContextBuilder builder, ScribNode visited) throws ScribbleException - { - JobContext jcontext = builder.job.getContext(); - ModuleContext mcontext = builder.getModuleContext(); - Do doo = (Do) visited; - ProtocolName pn = doo.proto.toName(); // leaveDisambiguation has fully qualified the target name - doo.roles.getRoles().forEach(r -> addProtocolDependency(builder, r, pn, doo.getTargetRoleParameter(jcontext, mcontext, r))); - return doo; - } - - protected abstract void addProtocolDependency(ProtocolDeclContextBuilder builder, Role self, ProtocolName proto, Role target); - - @Override - public void enterProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl) throws ScribbleException - { - super.enterProtocolInlining(parent, child, inl); - if (!inl.isCycle()) - { - SubprotocolSig subsig = inl.peekStack(); // SubprotocolVisitor has already entered subprotocol - inl.setSubprotocolRecVar(subsig); - } - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/HeaderParamDeclListDel.java b/scribble-core/src/main/java/org/scribble/del/HeaderParamDeclListDel.java deleted file mode 100644 index 86642d82f..000000000 --- a/scribble-core/src/main/java/org/scribble/del/HeaderParamDeclListDel.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.HeaderParamDecl; -import org.scribble.ast.HeaderParamDeclList; -import org.scribble.ast.ScribNode; -import org.scribble.main.ScribbleException; -import org.scribble.visit.wf.NameDisambiguator; - -public abstract class HeaderParamDeclListDel extends ScribDelBase -{ - public HeaderParamDeclListDel() - { - - } - - // Doing in leave allows the arguments to be individually checked first - @Override - public HeaderParamDeclList leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - HeaderParamDeclList pdl = (HeaderParamDeclList) visited; - List> decls = pdl.getDecls(); // grammar enforces RoleDeclList size > 0 - if (decls.size() != decls.stream().map((d) -> d.getDeclName()).distinct().count()) - { - throw new ScribbleException(pdl.getSource(), "Duplicate header decls: " + pdl); - } - return pdl; - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/InteractionNodeDel.java b/scribble-core/src/main/java/org/scribble/del/InteractionNodeDel.java deleted file mode 100644 index 603e8cc3f..000000000 --- a/scribble-core/src/main/java/org/scribble/del/InteractionNodeDel.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 InteractionNodeDel extends ScribDel -{ - -} diff --git a/scribble-core/src/main/java/org/scribble/del/InteractionSeqDel.java b/scribble-core/src/main/java/org/scribble/del/InteractionSeqDel.java deleted file mode 100644 index cfca6f341..000000000 --- a/scribble-core/src/main/java/org/scribble/del/InteractionSeqDel.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.main.ScribbleException; -import org.scribble.visit.ProtocolDefInliner; - -public abstract class InteractionSeqDel extends ScribDelBase -{ - @Override - public void enterProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl) throws ScribbleException - { - ScribDelBase.pushVisitorEnv(this, inl); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/InterruptibleDel.java b/scribble-core/src/main/java/org/scribble/del/InterruptibleDel.java deleted file mode 100644 index 34bd99a91..000000000 --- a/scribble-core/src/main/java/org/scribble/del/InterruptibleDel.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 InterruptibleDel extends CompoundInteractionNodeDel -{ - public InterruptibleDel() - { - - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/MessageTransferDel.java b/scribble-core/src/main/java/org/scribble/del/MessageTransferDel.java deleted file mode 100644 index 4dba242a1..000000000 --- a/scribble-core/src/main/java/org/scribble/del/MessageTransferDel.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.MessageSigNode; -import org.scribble.ast.MessageTransfer; -import org.scribble.ast.PayloadElem; -import org.scribble.ast.ScribNode; -import org.scribble.ast.global.GDelegationElem; -import org.scribble.del.global.GDelegationElemDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.MessageId; -import org.scribble.visit.InlinedProtocolUnfolder; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.ProtocolDeclContextBuilder; -import org.scribble.visit.env.UnfoldingEnv; -import org.scribble.visit.util.MessageIdCollector; -import org.scribble.visit.util.RoleCollector; - -public abstract class MessageTransferDel extends SimpleInteractionNodeDel -{ - public MessageTransferDel() - { - - } - - @Override - public MessageTransfer leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - MessageTransfer lr = (MessageTransfer) visited; - MessageTransfer inlined = (MessageTransfer) lr.clone(inl.job.af); - inl.pushEnv(inl.popEnv().setTranslation(inlined)); - return (MessageTransfer) super.leaveProtocolInlining(parent, child, inl, lr); - } - - /*@Override - public void enterChoiceUnguardedSubprotocolCheck(ScribNode parent, ScribNode child, ChoiceUnguardedSubprotocolChecker checker) throws ScribbleException - { - ChoiceUnguardedSubprotocolEnv env = checker.popEnv(); - env = env.disablePrune(); - checker.pushEnv(env); - }*/ - - @Override - public void enterInlinedProtocolUnfolding(ScribNode parent, ScribNode child, InlinedProtocolUnfolder unf) throws ScribbleException - { - UnfoldingEnv env = unf.popEnv(); - env = env.disableUnfold(); - unf.pushEnv(env); - } - - @Override - public ScribNode leaveRoleCollection(ScribNode parent, ScribNode child, RoleCollector coll, ScribNode visited) - { - MessageTransfer mt = (MessageTransfer) visited; - coll.addName(mt.src.toName()); - mt.getDestinationRoles().stream().forEach((rd) -> coll.addName(rd)); - return visited; - } - - @Override - public ScribNode leaveMessageIdCollection(ScribNode parent, ScribNode child, MessageIdCollector coll, ScribNode visited) - { - MessageTransfer mt = (MessageTransfer) visited; - if (mt.msg.isMessageSigNode() || mt.msg.isMessageSigNameNode()) - { - coll.addName((MessageId) mt.msg.toMessage().getId()); - } - else - { - throw new RuntimeException("Shouldn't get in here: " + mt.msg); - } - return visited; - } - - @Override - public MessageTransfer leaveProtocolDeclContextBuilding(ScribNode parent, ScribNode child, ProtocolDeclContextBuilder builder, ScribNode visited) throws ScribbleException - { - MessageTransfer mt = (MessageTransfer) visited; - if (mt.msg.isMessageSigNode()) - { - for (PayloadElem pe : ((MessageSigNode) mt.msg).payloads.getElements()) - { - if (pe.isGlobalDelegationElem()) // FIXME: should always be GMessageTransfer - { - ((GDelegationElemDel) pe.del()).leaveMessageTransferInProtocolDeclContextBuilding(mt, (GDelegationElem) pe, builder); - } - } - } - return mt; - } - - /*@Override - public ScribNode leaveEnablingMessageCollection(ScribNode parent, ScribNode child, EnablingMessageCollector coll, ScribNode visited) - { - MessageTransfer mt = (MessageTransfer) visited; - coll.addEnabling(mt.src.toName(), mt.getDestinations().get(0).toName(), mt.msg.toMessage().getId()); // FIXME: multicast - return visited; - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/del/ModuleDel.java b/scribble-core/src/main/java/org/scribble/del/ModuleDel.java deleted file mode 100644 index e1ef9744f..000000000 --- a/scribble-core/src/main/java/org/scribble/del/ModuleDel.java +++ /dev/null @@ -1,166 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Collection; -import java.util.HashSet; -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.ImportDecl; -import org.scribble.ast.Module; -import org.scribble.ast.ModuleDecl; -import org.scribble.ast.NonProtocolDecl; -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ModuleContext; -import org.scribble.ast.global.GProtocolDecl; -import org.scribble.ast.local.LProtocolDecl; -import org.scribble.ast.name.qualified.ModuleNameNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.LProtocolName; -import org.scribble.type.name.Role; -import org.scribble.visit.context.ModuleContextBuilder; -import org.scribble.visit.context.Projector; -import org.scribble.visit.wf.NameDisambiguator; - -public class ModuleDel extends ScribDelBase -{ - private ModuleContext mcontext; - - public ModuleDel() - { - - } - - private ModuleDel copy() - { - return new ModuleDel(); - } - - @Override - public void enterModuleContextBuilding(ScribNode parent, ScribNode child, ModuleContextBuilder builder) throws ScribbleException - { - builder.setModuleContext(new ModuleContext(builder.job.getContext(), (Module) child)); - } - - // Maybe better to create on enter, so can be used during the context build pass (Context would need to be "cached" in the visitor to be accessed) - @Override - public Module leaveModuleContextBuilding(ScribNode parent, ScribNode child, ModuleContextBuilder builder, ScribNode visited) throws ScribbleException - { - ModuleDel del = setModuleContext(builder.getModuleContext()); - return (Module) visited.del(del); - } - - @Override - public Module leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - Module mod = (Module) visited; - // Imports checked in ModuleContext -- that is built before disamb is run - List> npds = mod.getNonProtocolDecls(); - List npdnames = npds.stream().map((npd) -> npd.getDeclName().toString()).collect(Collectors.toList()); - // Have to use Strings, as can be different kinds (datatype, sig) - final Set dups1 = getDuplicates(npdnames); - //if (npds.size() != npdnames.stream().distinct().count()) - if (!dups1.isEmpty()) - { - NonProtocolDecl first = - npds.stream().filter((npd) -> dups1.contains(npd.getDeclName().toString())).collect(Collectors.toList()).get(0); - throw new ScribbleException(first.getSource(), "Duplicate non-protocol decls: " + first.getDeclName()); - } - List> pds = mod.getProtocolDecls(); - List pdnames = pds.stream().map((pd) -> pd.header.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()) - { - ProtocolDecl first = - pds.stream().filter((pd) -> dups2.contains(pd.header.getDeclName().toString())).collect(Collectors.toList()).get(0); - throw new ScribbleException(first.getSource(), "Duplicate protocol decls: " + first.header.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; - } - - @Override - public Module leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) - { - proj.job.getContext().addProjections(proj.getProjections()); - return (Module) visited; - } - - // lpd is the projected local protocol - public Module createModuleForProjection(Projector proj, Module root, GProtocolDecl gpd, LProtocolDecl lpd, Map> deps) - { - ModuleNameNode modname = Projector.makeProjectedModuleNameNode(proj.job.af, root.moddecl.name.getSource(), // Or ignore blame source for purely generated? - root.moddecl.getFullModuleName(), lpd.getHeader().getDeclName()); - ModuleDecl moddecl = proj.job.af.ModuleDecl(root.moddecl.getSource(), modname); - List> imports = new LinkedList<>(); - for (GProtocolName gpn : deps.keySet()) - { - for (Role role : deps.get(gpn)) - { - LProtocolName targetsimpname = Projector.projectSimpleProtocolName(gpn.getSimpleName(), role); - ModuleNameNode targetmodname = Projector.makeProjectedModuleNameNode(proj.job.af, null, // FIXME? projected import sources? - gpn.getPrefix(), targetsimpname); - if (!targetmodname.toName().equals(modname.toName())) // Self dependency -- each projected local is in its own module now, so can compare module names - { - imports.add(proj.job.af.ImportModule(null, targetmodname, null)); // FIXME? projected import sources? - } - } - } - - List> data = new LinkedList<>(root.getNonProtocolDecls()); // FIXME: copy? // FIXME: only project the dependencies - List> protos = Arrays.asList(lpd); - return proj.job.af.Module(gpd.header.getSource(), moddecl, imports, data, protos); - } - - @Override - public String toString() - { - return (this.mcontext == null) ? null : this.mcontext.toString(); // null before and during context building - } - - public ModuleContext getModuleContext() - { - return this.mcontext; - } - - protected ModuleDel setModuleContext(ModuleContext mcontext) - { - ModuleDel copy = copy(); // FIXME: should be a deep clone in principle - copy.mcontext = mcontext; - return copy; - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/NonRoleArgListDel.java b/scribble-core/src/main/java/org/scribble/del/NonRoleArgListDel.java deleted file mode 100644 index 79f7c93ed..000000000 --- a/scribble-core/src/main/java/org/scribble/del/NonRoleArgListDel.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.NonRoleParamDecl; -import org.scribble.ast.NonRoleParamDeclList; -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ScribNode; -import org.scribble.ast.name.simple.NonRoleParamNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.DataTypeKind; -import org.scribble.type.kind.NonRoleParamKind; -import org.scribble.type.kind.SigKind; -import org.scribble.visit.wf.NameDisambiguator; - -public class NonRoleArgListDel extends DoArgListDel -{ - public NonRoleArgListDel() - { - - } - - // Doing in leave allows the arguments to be individually checked first - @Override - public NonRoleArgList leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - NonRoleArgList nral = (NonRoleArgList) super.leaveDisambiguation(parent, child, disamb, visited); - // Checks matching arity - - ProtocolDecl pd = getTargetProtocolDecl((Do) parent, disamb); - Iterator args = nral.getDoArgs().iterator(); - for (NonRoleParamDecl param : pd.header.paramdecls.getDecls()) - { - NonRoleParamKind kind = param.kind; - NonRoleArg arg = args.next(); - if (arg.val.isParamNode()) - { - if (!((NonRoleParamNode) arg.val).kind.equals(kind)) - { - throw new ScribbleException(arg.getSource(), "Bad arg " + arg + " for param kind: " + kind); - } - } - else if (kind.equals(SigKind.KIND)) - { - if (!arg.val.isMessageSigNode() && !arg.val.isMessageSigNameNode()) - { - throw new ScribbleException(arg.getSource(), "Bad arg " + arg + " for param kind: " + kind); - } - } - else if (kind.equals(DataTypeKind.KIND)) - { - if (!arg.val.isDataTypeNameNode()) - { - throw new ScribbleException(arg.getSource(), "Bad arg " + arg + " for param kind: " + kind); - } - } - else - { - throw new RuntimeException("Shouldn't get in here: " + kind); - } - } - - return nral; - } - - @Override - protected NonRoleParamDeclList getParamDeclList(ProtocolDecl pd) - { - return pd.header.paramdecls; - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/ParallelDel.java b/scribble-core/src/main/java/org/scribble/del/ParallelDel.java deleted file mode 100644 index 05e6828a6..000000000 --- a/scribble-core/src/main/java/org/scribble/del/ParallelDel.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 ParallelDel extends CompoundInteractionNodeDel -{ - public ParallelDel() - { - - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/ProtocolBlockDel.java b/scribble-core/src/main/java/org/scribble/del/ProtocolBlockDel.java deleted file mode 100644 index 3c650e008..000000000 --- a/scribble-core/src/main/java/org/scribble/del/ProtocolBlockDel.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.main.ScribbleException; -import org.scribble.visit.ProtocolDefInliner; - -public abstract class ProtocolBlockDel extends CompoundInteractionDel -{ - @Override - public void enterProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl) throws ScribbleException - { - ScribDelBase.pushVisitorEnv(this, inl); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/ProtocolDeclDel.java b/scribble-core/src/main/java/org/scribble/del/ProtocolDeclDel.java deleted file mode 100644 index 8d9a66ffc..000000000 --- a/scribble-core/src/main/java/org/scribble/del/ProtocolDeclDel.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Set; - -import org.scribble.ast.Module; -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ProtocolDeclContext; -import org.scribble.main.ScribbleException; -import org.scribble.type.SubprotocolSig; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.MemberName; -import org.scribble.type.name.ProtocolName; -import org.scribble.type.name.Role; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.ProtocolDeclContextBuilder; -import org.scribble.visit.util.RoleCollector; -import org.scribble.visit.wf.NameDisambiguator; - -public abstract class ProtocolDeclDel extends ScribDelBase -{ - private ProtocolDeclContext pdcontext; - - protected ProtocolDeclDel() - { - - } - - protected abstract ProtocolDeclDel copy(); - - @Override - public ScribNode leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - disamb.clear(); - return visited; - } - - @Override - public void enterProtocolDeclContextBuilding(ScribNode parent, ScribNode child, ProtocolDeclContextBuilder builder) throws ScribbleException - { - builder.clearProtocolDependencies(); // collect per protocoldecl all together, do not clear? - - Module main = (Module) parent; - ProtocolDecl pd = (ProtocolDecl) child; - MemberName pn = pd.getFullMemberName(main); - // Is it really needed to add self protocoldecl dependencies? - pd.header.roledecls.getRoles().stream().forEach(r -> addSelfDependency(builder, (ProtocolName) pn, r)); - } - - protected abstract void addSelfDependency(ProtocolDeclContextBuilder builder, ProtocolName proto, Role role); - - @Override - public void enterProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl) throws ScribbleException - { - SubprotocolSig subsig = inl.peekStack(); // SubprotocolVisitor has already entered subprotocol - inl.setSubprotocolRecVar(subsig); - } - - @Override - public ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - return visited; - } - - @Override - public ScribNode leaveRoleCollection(ScribNode parent, ScribNode child, RoleCollector coll, ScribNode visited) throws ScribbleException - { - ProtocolDecl pd = (ProtocolDecl) visited; - Set occs = coll.getNames(); - // Needs ProtocolDeclContextBuilder to have built the context already - ProtocolDeclDel del = setProtocolDeclContext(getProtocolDeclContext().setRoleOccurrences(occs)); - return pd.del(del); - } - - public ProtocolDeclContext getProtocolDeclContext() - { - return this.pdcontext; - } - - protected ProtocolDeclDel setProtocolDeclContext(ProtocolDeclContext pdcontext) - { - ProtocolDeclDel copy = copy(); // FIXME: should be a deep clone in principle -- but if any other children are immutable, they can be shared - copy.pdcontext = pdcontext; - return copy; - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/ProtocolDefDel.java b/scribble-core/src/main/java/org/scribble/del/ProtocolDefDel.java deleted file mode 100644 index 487fc8032..000000000 --- a/scribble-core/src/main/java/org/scribble/del/ProtocolDefDel.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ProtocolDef; -import org.scribble.ast.ScribNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.RecRemover; -import org.scribble.visit.util.RecVarCollector; - -public abstract class ProtocolDefDel extends ScribDelBase -{ - protected ProtocolDef inlined = null; - - protected abstract ProtocolDefDel copy(); - - @Override - public void enterProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl) throws ScribbleException - { - ScribDelBase.pushVisitorEnv(this, inl); - } - - public ProtocolDef getInlinedProtocolDef() - { - return this.inlined; - } - - //public ProtocolDefDel setInlinedProtocolDef(ProtocolDef inlined) // Compiles in Eclipse, but not javac? wrt. subclass overriding - public ProtocolDefDel setInlinedProtocolDef(ProtocolDef inlined) - { - ProtocolDefDel copy = copy(); - copy.inlined = inlined; - return copy; - } - - public void enterRecRemoval(ScribNode parent, ScribNode child, RecRemover rem) - { - super.enterRecRemoval(parent, child, rem); - RecVarCollector rvc = new RecVarCollector(rem.job); - try - { - this.inlined.accept(rvc); // RecVarCollector not an InlinedProtocolVistor -- do simple visiting directly on inlined - } - catch (ScribbleException e) - { - throw new RuntimeException(e); - } - rem.setToRemove(rvc.getNames()); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/RecursionDel.java b/scribble-core/src/main/java/org/scribble/del/RecursionDel.java deleted file mode 100644 index 938d918ca..000000000 --- a/scribble-core/src/main/java/org/scribble/del/RecursionDel.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.main.ScribbleException; -import org.scribble.type.name.RecVar; -import org.scribble.visit.InlinedProtocolUnfolder; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.env.UnfoldingEnv; -import org.scribble.visit.util.RecVarCollector; -import org.scribble.visit.wf.NameDisambiguator; - -public abstract class RecursionDel extends CompoundInteractionNodeDel -{ - public RecursionDel() - { - - } - - @Override - public void enterDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb) throws ScribbleException - { - Recursion rec = (Recursion) child; - RecVar rv = rec.recvar.toName(); - /*if (disamb.isBoundRecVar(rv)) - { - throw new ScribbleException("Rec variable shadowing not currently allowed: " + rv); - // Inconsistent to disallow due to subprotocols and that NameDisambiguator is not an inlined or subprotocol visitor - }*/ - //disamb.addRecVar(rv); - disamb.pushRecVar(rv); - } - - @Override - public ScribNode leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - Recursion rec = (Recursion) visited; - /*RecVar rv = rec.recvar.toName(); - disamb.popRecVar(rv);*/ - RecVar rv = ((Recursion) child).recvar.toName(); // visited may be already name mangled // Not any more (refactored to inlining) - disamb.popRecVar(rv); - return rec; - } - - @Override - public void enterProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inliner) throws ScribbleException - { - super.enterProtocolInlining(parent, child, inliner); - Recursion rec = (Recursion) child; - inliner.pushRecVar(rec.recvar.toName()); - } - - @Override - public ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inliner, ScribNode visited) throws ScribbleException - { - //Recursion rec = (Recursion) visited; - RecVar origRV = ((Recursion) child).recvar.toName(); // visited may be already name mangled - inliner.popRecVar(origRV); - return super.leaveProtocolInlining(parent, child, inliner, visited); - } - - @Override - public void enterInlinedProtocolUnfolding(ScribNode parent, ScribNode child, InlinedProtocolUnfolder unf) throws ScribbleException - { - super.enterInlinedProtocolUnfolding(parent, child, unf); - Recursion lr = (Recursion) child; - RecVar recvar = lr.recvar.toName(); - unf.setRecVar(unf.job.af, recvar, lr); // Cloned on use (on continue) - } - - @Override - public Recursion leaveInlinedProtocolUnfolding(ScribNode parent, ScribNode child, InlinedProtocolUnfolder unf, ScribNode visited) throws ScribbleException - { - Recursion rec = (Recursion) visited; - RecVar recvar = rec.recvar.toName(); - unf.removeRecVar(recvar); - UnfoldingEnv merged = unf.popEnv().mergeContext((UnfoldingEnv) rec.block.del().env()); - unf.pushEnv(merged); - return (Recursion) super.leaveInlinedProtocolUnfolding(parent, child, unf, rec); - } - - /*@Override - public void enterChoiceUnguardedSubprotocolCheck(ScribNode parent, ScribNode child, ChoiceUnguardedSubprotocolChecker checker) throws ScribbleException - { - ScribDelBase.pushVisitorEnv(this, checker); - }*/ - - @Override - public void enterRecVarCollection(ScribNode parent, ScribNode child, RecVarCollector coll) - { - coll.addName(((Recursion) child).recvar.toName()); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/RoleArgListDel.java b/scribble-core/src/main/java/org/scribble/del/RoleArgListDel.java deleted file mode 100644 index 74ac569e8..000000000 --- a/scribble-core/src/main/java/org/scribble/del/RoleArgListDel.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ProtocolDecl; -import org.scribble.ast.RoleArgList; -import org.scribble.ast.RoleDeclList; -import org.scribble.ast.ScribNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.Role; -import org.scribble.visit.wf.NameDisambiguator; - -public class RoleArgListDel extends DoArgListDel -{ - public RoleArgListDel() - { - - } - - @Override - public RoleArgList leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - visited = super.leaveDisambiguation(parent, child, disamb, visited); - - // Duplicate check not needed for NonRoleArgList - RoleArgList ral = (RoleArgList) visited; - List roles = ral.getRoles(); - //if (roles.size() != new HashSet<>(roles).size()) - if (roles.size() != roles.stream().distinct().count()) - { - throw new ScribbleException(ral.getSource(), "Duplicate role args: " + roles); - } - return ral; - } - - @Override - protected RoleDeclList getParamDeclList(ProtocolDecl pd) - { - return pd.header.roledecls; - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/RoleDeclDel.java b/scribble-core/src/main/java/org/scribble/del/RoleDeclDel.java deleted file mode 100644 index 76aff676f..000000000 --- a/scribble-core/src/main/java/org/scribble/del/RoleDeclDel.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.main.ScribbleException; -import org.scribble.type.name.Role; -import org.scribble.visit.wf.NameDisambiguator; -import org.scribble.visit.wf.WFChoiceChecker; - -public class RoleDeclDel extends ScribDelBase -{ - @Override - public void enterDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb) throws ScribbleException - { - RoleDecl rd = (RoleDecl) child; - disamb.addRole(rd.getDeclName()); // Could check distinct here, but doing it uniformly in HeaderParamDeclListDel - } - - @Override - public RoleDecl leaveInlinedWFChoiceCheck(ScribNode parent, ScribNode child, WFChoiceChecker checker, ScribNode visited) throws ScribbleException - { - RoleDecl rd = (RoleDecl) visited; - Role role = rd.getDeclName(); - // enabled even for explicit connection protocols: otherwise no way to bootstrap initial connection(s) - checker.pushEnv(checker.popEnv().enableRoleForRootProtocolDecl(role)); - return (RoleDecl) super.leaveInlinedWFChoiceCheck(parent, child, checker, rd); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/ScribDel.java b/scribble-core/src/main/java/org/scribble/del/ScribDel.java deleted file mode 100644 index 63a50f148..000000000 --- a/scribble-core/src/main/java/org/scribble/del/ScribDel.java +++ /dev/null @@ -1,247 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.main.ScribbleException; -import org.scribble.visit.InlinedProtocolUnfolder; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.EGraphBuilder; -import org.scribble.visit.context.ModuleContextBuilder; -import org.scribble.visit.context.ProjectedChoiceDoPruner; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; -import org.scribble.visit.context.ProjectedRoleDeclFixer; -import org.scribble.visit.context.Projector; -import org.scribble.visit.context.ProtocolDeclContextBuilder; -import org.scribble.visit.context.RecRemover; -import org.scribble.visit.context.UnguardedChoiceDoProjectionChecker; -import org.scribble.visit.env.Env; -import org.scribble.visit.util.MessageIdCollector; -import org.scribble.visit.util.RecVarCollector; -import org.scribble.visit.util.RoleCollector; -import org.scribble.visit.validation.GProtocolValidator; -import org.scribble.visit.wf.DelegationProtocolRefChecker; -import org.scribble.visit.wf.ExplicitCorrelationChecker; -import org.scribble.visit.wf.NameDisambiguator; -import org.scribble.visit.wf.ReachabilityChecker; -import org.scribble.visit.wf.WFChoiceChecker; - -// Immutable except for pass-specific Envs (by visitors) only -- Envs considered transient, not treated immutably (i.e. non defensive setter on del) -// Parameterise by AstNode type? Would inhibit del sharing between types (but that's not currently needed) -public interface ScribDel -{ - Env env(); - void setEnv(Env env); // Non defensive - - default void enterModuleContextBuilding(ScribNode parent, ScribNode child, ModuleContextBuilder builder) throws ScribbleException - { - - } - - default ScribNode leaveModuleContextBuilding(ScribNode parent, ScribNode child, ModuleContextBuilder builder, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb) throws ScribbleException - { - - } - - default ScribNode leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterDelegationProtocolRefCheck(ScribNode parent, ScribNode child, DelegationProtocolRefChecker checker) throws ScribbleException - { - - } - - default ScribNode leaveDelegationProtocolRefCheck(ScribNode parent, ScribNode child, DelegationProtocolRefChecker checker, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterProtocolDeclContextBuilding(ScribNode parent, ScribNode child, ProtocolDeclContextBuilder builder) throws ScribbleException - { - - } - - default ScribNode leaveProtocolDeclContextBuilding(ScribNode parent, ScribNode child, ProtocolDeclContextBuilder builder, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterRoleCollection(ScribNode parent, ScribNode child, RoleCollector coll) - { - - } - - default ScribNode leaveRoleCollection(ScribNode parent, ScribNode child, RoleCollector coll, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl) throws ScribbleException - { - - } - - default ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterInlinedProtocolUnfolding(ScribNode parent, ScribNode child, InlinedProtocolUnfolder unf) throws ScribbleException - { - - } - - // These are for "choice-rec" unfolding, i.e. InlinedProtocolUnfolder -- cf. UnfoldingVisitor, which does continue unfolding by revisiting a clone of the rec body - default ScribNode leaveInlinedProtocolUnfolding(ScribNode parent, ScribNode child, InlinedProtocolUnfolder unf, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterInlinedWFChoiceCheck(ScribNode parent, ScribNode child, WFChoiceChecker checker) throws ScribbleException - { - - } - - default ScribNode leaveInlinedWFChoiceCheck(ScribNode parent, ScribNode child, WFChoiceChecker checker, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterProjection(ScribNode parent, ScribNode child, Projector proj) throws ScribbleException - { - - } - - default ScribNode leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterProjectedChoiceSubjectFixing(ScribNode parent, ScribNode child, ProjectedChoiceSubjectFixer fixer) - { - - } - - default ScribNode leaveProjectedChoiceSubjectFixing(ScribNode parent, ScribNode child, ProjectedChoiceSubjectFixer fixer, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterProjectedRoleDeclFixing(ScribNode parent, ScribNode child, ProjectedRoleDeclFixer fixer) - { - - } - - default ScribNode leaveProjectedRoleDeclFixing(ScribNode parent, ScribNode child, ProjectedRoleDeclFixer fixer, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterReachabilityCheck(ScribNode parent, ScribNode child, ReachabilityChecker checker) throws ScribbleException - { - - } - - default ScribNode leaveReachabilityCheck(ScribNode parent, ScribNode child, ReachabilityChecker checker, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder graph) - { - - } - - default ScribNode leaveEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder graph, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterMessageIdCollection(ScribNode parent, ScribNode child, MessageIdCollector coll) - { - - } - - default ScribNode leaveMessageIdCollection(ScribNode parent, ScribNode child, MessageIdCollector coll, ScribNode visited) - { - return visited; - } - - default void enterValidation(ScribNode parent, ScribNode child, GProtocolValidator coll) throws ScribbleException - { - - } - - default ScribNode leaveValidation(ScribNode parent, ScribNode child, GProtocolValidator coll, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterProjectedChoiceDoPruning(ScribNode parent, ScribNode child, ProjectedChoiceDoPruner pruner) throws ScribbleException - { - - } - - default ScribNode leaveProjectedChoiceDoPruning(ScribNode parent, ScribNode child, ProjectedChoiceDoPruner proj, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterUnguardedChoiceDoProjectionCheck(ScribNode parent, ScribNode child, UnguardedChoiceDoProjectionChecker checker) throws ScribbleException - { - - } - - default ScribNode leaveUnguardedChoiceDoProjectionCheck(ScribNode parent, ScribNode child, UnguardedChoiceDoProjectionChecker checker, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterExplicitCorrelationCheck(ScribNode parent, ScribNode child, ExplicitCorrelationChecker checker) throws ScribbleException - { - - } - - default ScribNode leaveExplicitCorrelationCheck(ScribNode parent, ScribNode child, ExplicitCorrelationChecker checker, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterRecVarCollection(ScribNode parent, ScribNode child, RecVarCollector coll) - { - - } - - default ScribNode leaveRecVarCollection(ScribNode parent, ScribNode child, RecVarCollector coll, ScribNode visited) throws ScribbleException - { - return visited; - } - - default void enterRecRemoval(ScribNode parent, ScribNode child, RecRemover rem) - { - - } - - default ScribNode leaveRecRemoval(ScribNode parent, ScribNode child, RecRemover rem, ScribNode visited) throws ScribbleException - { - return visited; - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/ScribDelBase.java b/scribble-core/src/main/java/org/scribble/del/ScribDelBase.java deleted file mode 100644 index 9c9f7d557..000000000 --- a/scribble-core/src/main/java/org/scribble/del/ScribDelBase.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.visit.EnvVisitor; -import org.scribble.visit.env.Env; - -// Mutable for pass-specific Envs (by visitors) -public abstract class ScribDelBase implements ScribDel -{ - private Env env; - - public ScribDelBase() - { - - } - - @Override - public Env env() - { - return this.env; - } - - // "setEnv" rather than "env" as a non-defensive setter (cf. ModelNodeBase#del) - @Override - //protected void setEnv(Env env) - public void setEnv(Env env) - { - this.env = env; - } - - public static > void pushVisitorEnv(ScribDel del, EnvVisitor ev) - { - T env = castEnv(ev, ev.peekEnv().enterContext()); // By default: copy - ev.pushEnv(env); - } - - public static , T2 extends ScribNode> - T2 popAndSetVisitorEnv(ScribDel del, EnvVisitor ev, T2 visited) - { - // No merge here: merging of child contexts into parent context is handled "manually" for each pass and (compound) interaction node as needed (e.g. WF-choice and reachability) - T1 env = ev.popEnv(); - ((ScribDelBase) del).setEnv(env); - return visited; - } - - private static > T castEnv(EnvVisitor ev, Env env) - { - @SuppressWarnings("unchecked") - T tmp = (T) env; - return tmp; - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/SimpleInteractionNodeDel.java b/scribble-core/src/main/java/org/scribble/del/SimpleInteractionNodeDel.java deleted file mode 100644 index 07922660a..000000000 --- a/scribble-core/src/main/java/org/scribble/del/SimpleInteractionNodeDel.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.main.ScribbleException; -import org.scribble.visit.ProtocolDefInliner; - -public abstract class SimpleInteractionNodeDel extends ScribDelBase implements InteractionNodeDel -{ - @Override - public void enterProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl) throws ScribbleException - { - ScribDelBase.pushVisitorEnv(this, inl); - } - - @Override - public ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - return ScribDelBase.popAndSetVisitorEnv(this, inl, visited); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GChoiceDel.java b/scribble-core/src/main/java/org/scribble/del/global/GChoiceDel.java deleted file mode 100644 index 7fdf44fdf..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GChoiceDel.java +++ /dev/null @@ -1,159 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Collections; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import org.scribble.ast.ScribNode; -import org.scribble.ast.global.GChoice; -import org.scribble.ast.global.GProtocolBlock; -import org.scribble.ast.local.LChoice; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ChoiceDel; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.Projector; -import org.scribble.visit.context.env.ProjectionEnv; -import org.scribble.visit.env.InlineProtocolEnv; -import org.scribble.visit.wf.WFChoiceChecker; -import org.scribble.visit.wf.env.WFChoiceEnv; - -public class GChoiceDel extends ChoiceDel implements GCompoundInteractionNodeDel -{ - @Override - public ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - GChoice gc = (GChoice) visited; - List blocks = gc.getBlocks().stream() - .map(b -> (GProtocolBlock) ((InlineProtocolEnv) b.del().env()).getTranslation()).collect(Collectors.toList()); - RoleNode subj = gc.subj.clone(inl.job.af); - GChoice inlined = inl.job.af.GChoice(gc.getSource(), subj, blocks); - inl.pushEnv(inl.popEnv().setTranslation(inlined)); - return (GChoice) super.leaveProtocolInlining(parent, child, inl, gc); - } - - @Override - public void enterInlinedWFChoiceCheck(ScribNode parent, ScribNode child, WFChoiceChecker checker) throws ScribbleException - { - // No super call -- replacing base routine with this one - WFChoiceEnv env = checker.peekEnv().enterContext(); - env = env.clear(); - env = env.enableChoiceSubject(((GChoice) child).subj.toName()); - checker.pushEnv(env); - } - - @Override - public GChoice leaveInlinedWFChoiceCheck(ScribNode parent, ScribNode child, WFChoiceChecker checker, ScribNode visited) throws ScribbleException - { - GChoice cho = (GChoice) visited; - Role subj = cho.subj.toName(); - if (!checker.peekParentEnv().isEnabled(subj)) - { - throw new ScribbleException(cho.subj.getSource(), "Subject not enabled: " + subj); - } - - // Enabled senders checked in GMessageTransferDel - List all = - cho.getBlocks().stream().map(b -> (WFChoiceEnv) b.del().env()).collect(Collectors.toList()); - if (checker.job.useOldWf) // **** - { - if (all.size() > 1) - { - try - { - WFChoiceEnv benv0 = all.get(0); - List benvs = all.subList(1, all.size()); - - Set dests = benv0.getEnabled().getDestinations(); - // Same roles enabled in every block - benvs.stream().map(e -> e.getEnabled().getDestinations()).forEach((rs) -> - { - if (!dests.equals(rs)) - { - throw new RuntimeScribbleException("Mismatched enabled roles: " + dests + ", " + rs); - } - }); - - dests.remove(subj); - for (Role dest : dests) - { - // Same enabler(s) for each enabled role - Set srcs = benv0.getEnabled().getSources(dest); // Always singleton? - benvs.stream().map(e -> e.getEnabled().getSources(dest)).forEach((rs) -> - { - if (!srcs.equals(rs)) - { - throw new RuntimeScribbleException("Mismatched enabler roles for " + dest + ": " + srcs + ", " + rs); - } - }); - - // Distinct enabling messages - Set> mids = benv0.getEnabled().getMessages(dest); - benvs.stream().map(e -> e.getEnabled().getMessages(dest)).forEach((ms) -> - { - if (!Collections.disjoint(mids, ms)) - { - throw new RuntimeScribbleException("Non disjoint enabling messages for " + dest + ": " + mids + ", " + ms); - } - mids.addAll(ms); - }); - } - } - catch (RuntimeScribbleException rse) // Lambda hack - { - throw new ScribbleException(rse.getMessage(), rse.getCause()); - } - } - } - - /*// No: do via Env merge, with "trinary state semantics" - ConnectedMap c0 = all.get(0).getConnected(); - //if (all.subList(1, all.size() - 1).stream().anyMatch((e) -> !c0.equals(e.getConnected()))) - for (WFChoiceEnv e : all.subList(1, all.size())) - { - ConnectedMap c = e.getConnected(); - if (!c0.equals(c)) - { - // FIXME: check on model? - throw new ScribbleException("Inconsistent connection configurations:\n " + c0 + "\n " + c); - } - }*/ - - // On leaving global choice, we're doing both the merging of block envs into the choice env, and the merging of the choice env to the parent-of-choice env - // In principle, for the envLeave we should only be doing the latter (as countpart to enterEnv), but it is much more convenient for the compound-node (choice) to collect all the child block envs and merge here, rather than each individual block env trying to (partially) merge into the parent-choice as they are visited - WFChoiceEnv merged = checker.popEnv().mergeContexts(all); - checker.pushEnv(merged); // Merges the child block envs into the current choice env; super call below merges this choice env into the parent env of the choice - return (GChoice) super.leaveInlinedWFChoiceCheck(parent, child, checker, visited); // Replaces base popAndSet to do pop, merge and set - // super call, unlike enter -- only leave is overridden in CompoundInteractionNodeDel, to do the "single" merge (cf. the "multiple" merge done above here) - } - - @Override - public GChoice leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) throws ScribbleException - { - GChoice gc = (GChoice) visited; - List blocks = - gc.getBlocks().stream().map(b -> (LProtocolBlock) ((ProjectionEnv) b.del().env()).getProjection()).collect(Collectors.toList()); - //gc.getBlocks().stream().map(b -> ((GProtocolBlockDel) b.del()).project(b, self)).collect(Collectors.toList()); - LChoice projection = gc.project(proj.job.af, proj.peekSelf(), blocks); - proj.pushEnv(proj.popEnv().setProjection(projection)); - return (GChoice) GCompoundInteractionNodeDel.super.leaveProjection(parent, child, proj, gc); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GCompoundInteractionNodeDel.java b/scribble-core/src/main/java/org/scribble/del/global/GCompoundInteractionNodeDel.java deleted file mode 100644 index 02d894107..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GCompoundInteractionNodeDel.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 GCompoundInteractionNodeDel extends GInteractionNodeDel -{ - -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GConnectDel.java b/scribble-core/src/main/java/org/scribble/del/global/GConnectDel.java deleted file mode 100644 index 19bfe071e..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GConnectDel.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.GConnect; -import org.scribble.ast.local.LNode; -import org.scribble.del.ConnectionActionDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; -import org.scribble.type.name.Role; -import org.scribble.visit.context.Projector; -import org.scribble.visit.wf.NameDisambiguator; -import org.scribble.visit.wf.WFChoiceChecker; -import org.scribble.visit.wf.env.WFChoiceEnv; - -public class GConnectDel extends ConnectionActionDel implements GSimpleInteractionNodeDel -{ - public GConnectDel() - { - - } - - @Override - public ScribNode leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - GConnect gc = (GConnect) visited; - /*Role src = gc.src.toName(); - Role dest = gc.dest.toName();*/ - return gc; - } - - @Override - public GConnect leaveInlinedWFChoiceCheck(ScribNode parent, ScribNode child, WFChoiceChecker checker, ScribNode visited) throws ScribbleException - { - GConnect gc = (GConnect) visited; - - Role src = gc.src.toName(); - if (!checker.peekEnv().isEnabled(src)) - { - throw new ScribbleException(gc.src.getSource(), "Role not enabled: " + src); - } - Message msg = gc.msg.toMessage(); - WFChoiceEnv env = checker.popEnv(); - //for (Role dest : gc.getDestinationRoles()) - Role dest = gc.dest.toName(); - { - if (src.equals(dest)) - { - throw new ScribbleException(gc.getSource(), "[TODO] Self connections not supported: " + gc); - } - if (env.isConnected(src, dest)) - { - throw new ScribbleException(gc.getSource(), "Roles (possibly) already connected: " + src + ", " + dest); - } - - env = env.connect(src, dest).addMessage(src, dest, msg); - /*env = env - .connect(src, dest) - .addMessage(src, dest, new MessageSig(Op.EMPTY_OPERATOR, Payload.EMPTY_PAYLOAD));*/ - } - checker.pushEnv(env); - return gc; - } - - @Override - public ScribNode leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) throws ScribbleException //throws ScribbleException - { - GConnect gc = (GConnect) visited; - Role self = proj.peekSelf(); - LNode projection = gc.project(proj.job.af, self); - proj.pushEnv(proj.popEnv().setProjection(projection)); - return (GConnect) GSimpleInteractionNodeDel.super.leaveProjection(parent, child, proj, gc); - } - - /*// Duplicated from GMessageTransferDel - @Override - public ScribNode leaveF17Parsing(ScribNode parent, ScribNode child, F17Parser parser, ScribNode visited) throws ScribbleException - { - F17ParserEnv env = parser.peekEnv(); - if (env.isUnguarded()) - { - parser.popEnv(); - parser.pushEnv(new F17ParserEnv()); // Maybe make "setGuarded" method - } - return super.leaveF17Parsing(parent, child, parser, visited); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GContinueDel.java b/scribble-core/src/main/java/org/scribble/del/global/GContinueDel.java deleted file mode 100644 index fa8d6796d..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GContinueDel.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ast.local.LContinue; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.del.ContinueDel; -import org.scribble.main.ScribbleException; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.Projector; -import org.scribble.visit.env.InlineProtocolEnv; - -public class GContinueDel extends ContinueDel implements GSimpleInteractionNodeDel -{ - @Override - public GContinue leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - GContinue gc = (GContinue) visited; - RecVarNode recvar = (RecVarNode) ((InlineProtocolEnv) gc.recvar.del().env()).getTranslation(); - GContinue inlined = inl.job.af.GContinue(gc.getSource(), recvar); - inl.pushEnv(inl.popEnv().setTranslation(inlined)); - return (GContinue) super.leaveProtocolInlining(parent, child, inl, gc); - } - - /*public LContinue project(AstFactory af, GNode n, Role self) - { - GContinue gc = (GContinue) n; - LContinue projection = gc.project(af, self); - return projection; - }*/ - - @Override - public GContinue leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) throws ScribbleException - { - GContinue gc = (GContinue) visited; - //LContinue projection = project(proj.job.af, gc, proj.peekSelf()); - LContinue projection = gc.project(proj.job.af, proj.peekSelf()); - proj.pushEnv(proj.popEnv().setProjection(projection)); - return (GContinue) GSimpleInteractionNodeDel.super.leaveProjection(parent, child, proj, gc); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GDelegationElemDel.java b/scribble-core/src/main/java/org/scribble/del/global/GDelegationElemDel.java deleted file mode 100644 index ba9656a43..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GDelegationElemDel.java +++ /dev/null @@ -1,143 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.HashSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.stream.Collectors; - -import org.scribble.ast.MessageTransfer; -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ModuleContext; -import org.scribble.ast.global.GDelegationElem; -import org.scribble.ast.name.qualified.GProtocolNameNode; -import org.scribble.del.ScribDelBase; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.Global; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.ProtocolName; -import org.scribble.type.name.Role; -import org.scribble.visit.context.ProtocolDeclContextBuilder; -import org.scribble.visit.wf.DelegationProtocolRefChecker; -import org.scribble.visit.wf.NameDisambiguator; - -public class GDelegationElemDel extends ScribDelBase -{ - public GDelegationElemDel() - { - - } - - // Duplicated from DoDel - @Override - public void enterDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb) throws ScribbleException - { - ModuleContext mc = disamb.getModuleContext(); - GDelegationElem de = (GDelegationElem) child; - GProtocolName gpn = de.proto.toName(); - if (!mc.isVisibleProtocolDeclName(gpn)) - { - throw new ScribbleException(de.proto.getSource(), "Protocol decl not visible: " + gpn); - } - } - - // Duplicated from DoDel - //@Override - //public ScribNode leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - public GDelegationElem visitForNameDisambiguation(NameDisambiguator disamb, GDelegationElem de) throws ScribbleException - { - //DelegationElem de = (DelegationElem) visited; - ModuleContext mc = disamb.getModuleContext(); - GProtocolName fullname = (GProtocolName) mc.getVisibleProtocolDeclFullName(de.proto.toName()); - - Role rn = de.role.toName(); - ProtocolDecl gpd = disamb.job.getContext().getModule(fullname.getPrefix()).getProtocolDecl(fullname.getSimpleName()); - if (!gpd.header.roledecls.getRoles().contains(rn)) - { - throw new ScribbleException(de.role.getSource(), "Invalid delegation role: " + de); - } - - GProtocolNameNode pnn = (GProtocolNameNode) disamb.job.af.QualifiedNameNode(de.proto.getSource(), fullname.getKind(), fullname.getElements()); // Not keeping original namenode del - return de.reconstruct(pnn, de.role); - } - - /*// Is this needed? Or DataTypeNodes always created from AmbigNameNode? (in this same pass) - @Override - public ScribNode leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) - throws ScribbleException - { - ModuleContext mc = disamb.getModuleContext(); - DataTypeNode dtn = (DataTypeNode) visited; - DataType fullname = mc.getVisibleDataTypeFullName(dtn.toName()); - return (DataTypeNode) - AstFactoryImpl.FACTORY.QualifiedNameNode(DataTypeKind.KIND, fullname.getElements()); // Didn't keep original del - }*/ - - //@Override - //public DelegationElem leaveProtocolDeclContextBuilding(ScribNodeScribNode parent, ScribNode child, ProtocolDeclContextBuilder builder, ScribNode visited) throws ScribbleException // FIXME: cannot access MessageTransfer roles from here - // FIXME: apply this pattern (delegate from parent back to child class) to all other existing instances - // FIXME: should always be GMessageTransfer - public void leaveMessageTransferInProtocolDeclContextBuilding(MessageTransfer mt, GDelegationElem de, ProtocolDeclContextBuilder builder) throws ScribbleException - { - GProtocolName gpn = de.proto.toName(); // leaveDisambiguation has fully qualified the target name - builder.addGlobalProtocolDependency(mt.src.toName(), gpn, de.role.toName()); // FIXME: does it make sense to use projection role as dependency target role? (seems to be used for Job.getProjections) - mt.getDestinationRoles().forEach((r) -> builder.addGlobalProtocolDependency(r, gpn, de.role.toName())); - } - - @Override - public void enterDelegationProtocolRefCheck(ScribNode parent, ScribNode child, DelegationProtocolRefChecker checker) throws ScribbleException - { - GDelegationElem de = (GDelegationElem) child; - ModuleContext mc = checker.getModuleContext(); - GProtocolName targetfullname = (GProtocolName) mc.getVisibleProtocolDeclFullName(de.proto.toName()); - GProtocolName rootfullname = (GProtocolName) mc.getVisibleProtocolDeclFullName(checker.getProtocolDeclOnEntry().header.getDeclName()); - if (targetfullname.equals(rootfullname)) // Explicit check here because ProtocolDeclContextBuilder dependencies explicitly include self protocoldecl dependencies (cf. GProtocolDeclDel.addSelfDependency) - { - throw new ScribbleException(de.getSource(), "Recursive protocol dependencies not supported for delegation types: " + de); - } - - Set todo = new LinkedHashSet(); - ProtocolDecl targetgpd = checker.job.getContext().getModule(targetfullname.getPrefix()).getProtocolDecl(targetfullname.getSimpleName()); // target - // FIXME: does this already contain transitive do-dependencies? But doesn't contain transitive delegation-dependencies..? - Set init = - ((GProtocolDeclDel) targetgpd.del()).getProtocolDeclContext().getDependencyMap().getDependencies() - .values().stream().flatMap((v) -> v.keySet().stream()).collect(Collectors.toSet()); - todo.addAll(init); - - Set seen = new HashSet<>(); - while (!todo.isEmpty()) - { - Iterator it = todo.iterator(); - GProtocolName next = it.next(); - it.remove(); - seen.add(next); - - ProtocolName nextfullname = mc.getVisibleProtocolDeclFullName(next); - if (rootfullname.equals(nextfullname)) - { - throw new ScribbleException(de.getSource(), "Recursive protocol dependencies not supported for delegation types: " + de); - } - ProtocolDecl nextgpd = checker.job.getContext().getModule(targetfullname.getPrefix()).getProtocolDecl(nextfullname.getSimpleName()); - Set tmp = - ((GProtocolDeclDel) nextgpd.del()).getProtocolDeclContext().getDependencyMap().getDependencies() - .values().stream().flatMap((v) -> v.keySet().stream()) - .filter((n) -> !seen.contains(n)) - .collect(Collectors.toSet()); - todo.addAll(tmp); - } - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GDisconnectDel.java b/scribble-core/src/main/java/org/scribble/del/global/GDisconnectDel.java deleted file mode 100644 index 9fad4b3f2..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GDisconnectDel.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ast.local.LNode; -import org.scribble.del.ConnectionActionDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.Role; -import org.scribble.visit.context.Projector; -import org.scribble.visit.wf.NameDisambiguator; -import org.scribble.visit.wf.WFChoiceChecker; -import org.scribble.visit.wf.env.WFChoiceEnv; - -// FIXME: make DisconnectDel (cf., G/LMessageTransferDel) -public class GDisconnectDel extends ConnectionActionDel implements GSimpleInteractionNodeDel -{ - public GDisconnectDel() - { - - } - - @Override - public ScribNode leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - GDisconnect gc = (GDisconnect) visited; - /*Role src = gc.src.toName(); - Role dest = gc.dest.toName();*/ - return gc; - } - - @Override - public GDisconnect leaveInlinedWFChoiceCheck(ScribNode parent, ScribNode child, WFChoiceChecker checker, ScribNode visited) throws ScribbleException - { - GDisconnect gd = (GDisconnect) visited; - - Role src = gd.src.toName(); - if (!checker.peekEnv().isEnabled(src)) - { - throw new ScribbleException(gd.src.getSource(), "Role not enabled: " + src); - } - //Message msg = gd.msg.toMessage(); // Unit message - WFChoiceEnv env = checker.popEnv(); - //for (Role dest : gc.getDestinationRoles()) - Role dest = gd.dest.toName(); - if (!env.isEnabled(dest)) - { - throw new ScribbleException(gd.dest.getSource(), "Role not enabled: " + dest); - } - { - if (src.equals(dest)) - { - throw new ScribbleException(gd.getSource(), "[TODO] Self connections not supported: " + gd); // Would currently be subsumed by the below - } - if (!env.isConnected(src, dest)) - { - throw new ScribbleException(gd.getSource(), "Roles not (necessarily) connected: " + src + ", " + dest); - } - - env = env.disconnect(src, dest);//.removeMessage(src, dest, ...); // Is remove really needed? - /*env = env - .disconnect(src, dest) - .removeMessage(src, dest, new MessageSig(Op.EMPTY_OPERATOR, Payload.EMPTY_PAYLOAD)); // FIXME: factor out dummy connection message with GConnect etc.*/ - } - checker.pushEnv(env); - return gd; - } - - @Override - public ScribNode leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) throws ScribbleException //throws ScribbleException - { - GDisconnect gd = (GDisconnect) visited; - Role self = proj.peekSelf(); - LNode projection = gd.project(proj.job.af, self); - proj.pushEnv(proj.popEnv().setProjection(projection)); - return (GDisconnect) GSimpleInteractionNodeDel.super.leaveProjection(parent, child, proj, gd); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GDoDel.java b/scribble-core/src/main/java/org/scribble/del/global/GDoDel.java deleted file mode 100644 index f041f3ff1..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GDoDel.java +++ /dev/null @@ -1,114 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.antlr.runtime.tree.CommonTree; -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ModuleContext; -import org.scribble.ast.global.GContinue; -import org.scribble.ast.global.GDo; -import org.scribble.ast.global.GInteractionSeq; -import org.scribble.ast.global.GProtocolBlock; -import org.scribble.ast.global.GRecursion; -import org.scribble.ast.local.LDo; -import org.scribble.ast.name.qualified.LProtocolNameNode; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.del.DoDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.SubprotocolSig; -import org.scribble.type.kind.RecVarKind; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.ProtocolName; -import org.scribble.type.name.Role; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.Projector; -import org.scribble.visit.context.ProtocolDeclContextBuilder; -import org.scribble.visit.env.InlineProtocolEnv; - -public class GDoDel extends DoDel implements GSimpleInteractionNodeDel -{ - // Part of context building - @Override - protected void addProtocolDependency(ProtocolDeclContextBuilder builder, Role self, ProtocolName proto, Role target) - { - builder.addGlobalProtocolDependency(self, (GProtocolName) proto, target); - } - - // Only called if cycle - public GDo visitForSubprotocolInlining(ProtocolDefInliner builder, GDo child) - { - CommonTree blame = child.getSource(); - SubprotocolSig subsig = builder.peekStack(); - RecVarNode recvar = (RecVarNode) builder.job.af.SimpleNameNode(blame, RecVarKind.KIND, builder.getSubprotocolRecVar(subsig).toString()); - GContinue inlined = builder.job.af.GContinue(blame, recvar); - builder.pushEnv(builder.popEnv().setTranslation(inlined)); - return child; - } - - @Override - public GDo leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - if (!inl.isCycle()) - { - CommonTree blame = visited.getSource(); - SubprotocolSig subsig = inl.peekStack(); - RecVarNode recvar = (RecVarNode) inl.job.af.SimpleNameNode(blame, RecVarKind.KIND, inl.getSubprotocolRecVar(subsig).toString()); - GInteractionSeq gis = (GInteractionSeq) (((InlineProtocolEnv) inl.peekEnv()).getTranslation()); - GProtocolBlock gb = inl.job.af.GProtocolBlock(blame, gis); - GRecursion inlined = inl.job.af.GRecursion(blame, recvar, gb); - inl.pushEnv(inl.popEnv().setTranslation(inlined)); - inl.removeSubprotocolRecVar(subsig); - } - return (GDo) super.leaveProtocolInlining(parent, child, inl, visited); - } - - @Override - public void enterProjection(ScribNode parent, ScribNode child, Projector proj) throws ScribbleException - { - GSimpleInteractionNodeDel.super.enterProjection(parent, child, proj); - - GDo gd = (GDo) child; - Role self = proj.peekSelf(); - if (gd.roles.getRoles().contains(self)) - { - // For correct name mangling, need to use the parameter corresponding to the self argument - // N.B. -- this depends on Projector not following the Subprotocol pattern, otherwise self is wrong - Role param = gd.getTargetRoleParameter(proj.job.getContext(), proj.getModuleContext(), self); - proj.pushSelf(param); - } - else - { - proj.pushSelf(self); // Dummy: just to make pop in leave work - } - } - - @Override - public GDo leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) throws ScribbleException //throws ScribbleException - { - GDo gd = (GDo) visited; - Role popped = proj.popSelf(); - Role self = proj.peekSelf(); - LDo projection = null; - if (gd.roles.getRoles().contains(self)) - { - ModuleContext mc = proj.getModuleContext(); - LProtocolNameNode target = Projector.makeProjectedFullNameNode(proj.job.af, gd.proto.getSource(), gd.getTargetProtocolDeclFullName(mc), popped); - projection = gd.project(proj.job.af, self, target); - - // FIXME: do guarded recursive subprotocol checking (i.e. role is used during chain) in reachability checking? -- required role-usage makes local choice subject inference easier, but is restrictive (e.g. proto(A, B, C) { choice at A {A->B.do Proto(A,B,C)} or {A->B.B->C} })) - } - proj.pushEnv(proj.popEnv().setProjection(projection)); - return (GDo) GSimpleInteractionNodeDel.super.leaveProjection(parent, child, proj, gd); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GInteractionNodeDel.java b/scribble-core/src/main/java/org/scribble/del/global/GInteractionNodeDel.java deleted file mode 100644 index 5bad89bd7..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GInteractionNodeDel.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.del.InteractionNodeDel; -import org.scribble.del.ScribDelBase; -import org.scribble.main.ScribbleException; -import org.scribble.visit.context.Projector; - -public interface GInteractionNodeDel extends InteractionNodeDel -{ - //public abstract LNode project(GNode n, Role self); // Generalised return, e.g. returning a seq - - @Override - default void enterProjection(ScribNode parent, ScribNode child, Projector proj) throws ScribbleException - { - ScribDelBase.pushVisitorEnv(this, proj); - } - - @Override - default ScribNode leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) throws ScribbleException - { - return ScribDelBase.popAndSetVisitorEnv(this, proj, visited); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GInteractionSeqDel.java b/scribble-core/src/main/java/org/scribble/del/global/GInteractionSeqDel.java deleted file mode 100644 index d493b6699..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GInteractionSeqDel.java +++ /dev/null @@ -1,137 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.scribble.ast.ScribNode; -import org.scribble.ast.global.GInteractionNode; -import org.scribble.ast.global.GInteractionSeq; -import org.scribble.ast.global.GRecursion; -import org.scribble.ast.local.LInteractionNode; -import org.scribble.ast.local.LInteractionSeq; -import org.scribble.ast.local.LNode; -import org.scribble.del.InteractionSeqDel; -import org.scribble.del.ScribDelBase; -import org.scribble.main.ScribbleException; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.Projector; -import org.scribble.visit.context.RecRemover; -import org.scribble.visit.context.env.ProjectionEnv; -import org.scribble.visit.env.InlineProtocolEnv; - -public class GInteractionSeqDel extends InteractionSeqDel -{ - // enter in super - @Override - public ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - GInteractionSeq gis = (GInteractionSeq) visited; - List gins = new LinkedList(); - for (GInteractionNode gi : gis.getInteractions()) - { - ScribNode inlined = ((InlineProtocolEnv) gi.del().env()).getTranslation(); - if (inlined instanceof GInteractionSeq) // A do got inlined - { - gins.addAll(((GInteractionSeq) inlined).getInteractions()); - } - else - { - gins.add((GInteractionNode) inlined); - } - } - GInteractionSeq inlined = inl.job.af.GInteractionSeq(gis.getSource(), gins); - inl.pushEnv(inl.popEnv().setTranslation(inlined)); - return (GInteractionSeq) ScribDelBase.popAndSetVisitorEnv(this, inl, gis); - } - - @Override - public void enterProjection(ScribNode parent, ScribNode child, Projector proj) throws ScribbleException - { - ScribDelBase.pushVisitorEnv(this, proj); // Unlike WF-choice and Reachability, Projection uses an Env for InteractionSequences - } - - @Override - public GInteractionSeq leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) throws ScribbleException - { - GInteractionSeq gis = (GInteractionSeq) visited; - List lis = new LinkedList<>(); - for (GInteractionNode gi : gis.getInteractions()) // FIXME: rewrite using flatMap - { - LNode ln = (LNode) ((ProjectionEnv) gi.del().env()).getProjection(); - //LNode ln = ((GInteractionNodeDel) gi.del()).project(gi, self); // FIXME: won't work for do - // FIXME: move node-specific projects to G nodes (not dels) and take child projections as params, bit like reconstruct - if (ln instanceof LInteractionSeq) // Self comm sequence - { - lis.addAll(((LInteractionSeq) ln).getInteractions()); - } - else if (ln != null) // null is used for empty projection - { - lis.add((LInteractionNode) ln); - } - } - /*if (lis.size() == 1) // NO: needed for e.g. rec X { 1() from A to B; choice at A { continue X; } or { 2() from A to B; } } -- do instead in GRecursion - { - if (lis.get(0) instanceof Continue) - { - lis.clear(); - } - }*/ - LInteractionSeq projection = gis.project(proj.job.af, proj.peekSelf(), lis); - proj.pushEnv(proj.popEnv().setProjection(projection)); - return (GInteractionSeq) ScribDelBase.popAndSetVisitorEnv(this, proj, gis); - } - - /*@Override - public GInteractionSeq leaveF17Parsing(ScribNode parent, ScribNode child, F17Parser parser, ScribNode visited) throws ScribbleException - { - GInteractionSeq gis = (GInteractionSeq) visited; - List gins = gis.getInteractions(); - Iterator i = gins.iterator(); - while (i.hasNext()) - { - GInteractionNode gin = i.next(); - if (!i.hasNext()) - { - break; - } - /*F17ParserEnv env = (F17ParserEnv) gin.del().env(); - if (env.isUnguarded()) - { - throw new ScribbleException("[FASE17] unguarded choice case: " + gin); - }* / - if (!(gin instanceof GMessageTransfer || gin instanceof GConnect || gin instanceof GDisconnect)) - { - throw new ScribbleException("[FASE17] Bad sequence composition following:\n" + gin); - } - } - return gis; - }*/ - - @Override - public GInteractionSeq leaveRecRemoval(ScribNode parent, ScribNode child, RecRemover rem, ScribNode visited) - throws ScribbleException - { - GInteractionSeq gis = (GInteractionSeq) visited; - List gins = gis.getInteractions().stream().flatMap((gi) -> - (gi instanceof GRecursion && rem.toRemove(((GRecursion) gi).recvar.toName())) - ? ((GRecursion) gi).getBlock().getInteractionSeq().getInteractions().stream() - : Stream.of(gi) - ).collect(Collectors.toList()); - return rem.job.af.GInteractionSeq(gis.getSource(), gins); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GInterruptibleDel.java b/scribble-core/src/main/java/org/scribble/del/global/GInterruptibleDel.java deleted file mode 100644 index 6b8cc83e2..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GInterruptibleDel.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.InterruptibleDel; - -public class GInterruptibleDel extends InterruptibleDel implements GCompoundInteractionNodeDel -{ - -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GMessageTransferDel.java b/scribble-core/src/main/java/org/scribble/del/global/GMessageTransferDel.java deleted file mode 100644 index e605a16af..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GMessageTransferDel.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.GMessageTransfer; -import org.scribble.ast.local.LNode; -import org.scribble.del.MessageTransferDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.Message; -import org.scribble.type.name.Role; -import org.scribble.visit.context.Projector; -import org.scribble.visit.wf.NameDisambiguator; -import org.scribble.visit.wf.WFChoiceChecker; -import org.scribble.visit.wf.env.WFChoiceEnv; - -public class GMessageTransferDel extends MessageTransferDel implements GSimpleInteractionNodeDel -{ - public GMessageTransferDel() - { - - } - - @Override - public ScribNode leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - GMessageTransfer gmt = (GMessageTransfer) visited; - Role src = gmt.src.toName(); - List dests = gmt.getDestinationRoles(); - if (dests.contains(src)) - { - throw new ScribbleException(gmt.getSource(), "[TODO] Self connections not supported: " + gmt); // Would currently be subsumed by unconnected check - } - return gmt; - } - - @Override - public GMessageTransfer leaveInlinedWFChoiceCheck(ScribNode parent, ScribNode child, WFChoiceChecker checker, ScribNode visited) throws ScribbleException - { - GMessageTransfer gmt = (GMessageTransfer) visited; - - Role src = gmt.src.toName(); - if (!checker.peekEnv().isEnabled(src)) - { - throw new ScribbleException(gmt.src.getSource(), "Role not enabled: " + src); - } - Message msg = gmt.msg.toMessage(); - WFChoiceEnv env = checker.popEnv(); - for (Role dest : gmt.getDestinationRoles()) - { - // FIXME: better to check as global model error (role stuck on uncomnected send) - if (!env.isConnected(src, dest)) - { - throw new ScribbleException(gmt.getSource(), "Roles not (necessarily) connected: " + src + ", " + dest); - } - - env = env.addMessage(src, dest, msg); - - //System.out.println("a: " + src + ", " + dest + ", " + msg); - } - checker.pushEnv(env); - return gmt; - } - - @Override - //public GMessageTransfer leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) throws ScribbleException //throws ScribbleException - public ScribNode leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) throws ScribbleException //throws ScribbleException - { - GMessageTransfer gmt = (GMessageTransfer) visited; - Role self = proj.peekSelf(); - LNode projection = gmt.project(proj.job.af, self); - proj.pushEnv(proj.popEnv().setProjection(projection)); - return (GMessageTransfer) GSimpleInteractionNodeDel.super.leaveProjection(parent, child, proj, gmt); - } - - /*@Override - public ScribNode leaveF17Parsing(ScribNode parent, ScribNode child, F17Parser parser, ScribNode visited) throws ScribbleException - { - F17ParserEnv env = parser.peekEnv(); - if (env.isUnguarded()) - { - parser.popEnv(); - parser.pushEnv(new F17ParserEnv()); // Maybe make "setGuarded" method - } - return super.leaveF17Parsing(parent, child, parser, visited); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GParallelDel.java b/scribble-core/src/main/java/org/scribble/del/global/GParallelDel.java deleted file mode 100644 index 9ddca9308..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GParallelDel.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ParallelDel; - -public class GParallelDel extends ParallelDel implements GCompoundInteractionNodeDel -{ - -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GProtocolBlockDel.java b/scribble-core/src/main/java/org/scribble/del/global/GProtocolBlockDel.java deleted file mode 100644 index 90c8f37ee..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GProtocolBlockDel.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.GInteractionSeq; -import org.scribble.ast.global.GProtocolBlock; -import org.scribble.ast.local.LInteractionSeq; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.del.ProtocolBlockDel; -import org.scribble.del.ScribDelBase; -import org.scribble.main.ScribbleException; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.Projector; -import org.scribble.visit.context.env.ProjectionEnv; -import org.scribble.visit.env.InlineProtocolEnv; - -public class GProtocolBlockDel extends ProtocolBlockDel -{ - - @Override - public ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - GProtocolBlock gpb = (GProtocolBlock) visited; - GInteractionSeq seq = (GInteractionSeq) ((InlineProtocolEnv) gpb.seq.del().env()).getTranslation(); - GProtocolBlock inlined = inl.job.af.GProtocolBlock(gpb.getSource(), seq); - inl.pushEnv(inl.popEnv().setTranslation(inlined)); - return (GProtocolBlock) ScribDelBase.popAndSetVisitorEnv(this, inl, gpb); - } - - @Override - public void enterProjection(ScribNode parent, ScribNode child, Projector proj) throws ScribbleException - { - ScribDelBase.pushVisitorEnv(this, proj); - } - - @Override - public GProtocolBlock leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) throws ScribbleException - { - GProtocolBlock gpb = (GProtocolBlock) visited; - LInteractionSeq seq = - (LInteractionSeq) ((ProjectionEnv) gpb.seq.del().env()).getProjection(); - //((GInteractionSeqDel) gpb.seq.del()).project(gpb.getInteractionSeq(), self); - LProtocolBlock projection = gpb.project(proj.job.af, proj.peekSelf(), seq); - proj.pushEnv(proj.popEnv().setProjection(projection)); - return (GProtocolBlock) ScribDelBase.popAndSetVisitorEnv(this, proj, gpb); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GProtocolDeclDel.java b/scribble-core/src/main/java/org/scribble/del/global/GProtocolDeclDel.java deleted file mode 100644 index 1e39d9e5e..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GProtocolDeclDel.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Map; -import java.util.Set; - -import org.scribble.ast.AstFactory; -import org.scribble.ast.Module; -import org.scribble.ast.NonRoleParamDeclList; -import org.scribble.ast.RoleDeclList; -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.DependencyMap; -import org.scribble.ast.context.global.GProtocolDeclContext; -import org.scribble.ast.global.GProtocolDecl; -import org.scribble.ast.global.GProtocolHeader; -import org.scribble.ast.local.LProtocolDecl; -import org.scribble.ast.local.LProtocolDef; -import org.scribble.ast.local.LProtocolHeader; -import org.scribble.ast.name.qualified.LProtocolNameNode; -import org.scribble.del.ModuleDel; -import org.scribble.del.ProtocolDeclDel; -import org.scribble.main.Job; -import org.scribble.main.JobContext; -import org.scribble.main.ScribbleException; -import org.scribble.model.global.SGraph; -import org.scribble.type.kind.Global; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.ProtocolName; -import org.scribble.type.name.Role; -import org.scribble.visit.context.Projector; -import org.scribble.visit.context.ProtocolDeclContextBuilder; -import org.scribble.visit.context.env.ProjectionEnv; -import org.scribble.visit.util.RoleCollector; -import org.scribble.visit.validation.GProtocolValidator; - -public class GProtocolDeclDel extends ProtocolDeclDel -{ - public GProtocolDeclDel() - { - - } - - @Override - public GProtocolDeclContext getProtocolDeclContext() - { - return (GProtocolDeclContext) super.getProtocolDeclContext(); - } - - @Override - protected GProtocolDeclDel copy() - { - return new GProtocolDeclDel(); - } - - @Override - protected void addSelfDependency(ProtocolDeclContextBuilder builder, ProtocolName proto, Role role) - { - builder.addGlobalProtocolDependency(role, (GProtocolName) proto, role); - } - - @Override - public GProtocolDecl - leaveProtocolDeclContextBuilding(ScribNode parent, ScribNode child, ProtocolDeclContextBuilder builder, ScribNode visited) throws ScribbleException - { - GProtocolDecl gpd = (GProtocolDecl) visited; - GProtocolDeclContext gcontext = new GProtocolDeclContext(builder.getGlobalProtocolDependencyMap()); - GProtocolDeclDel del = (GProtocolDeclDel) setProtocolDeclContext(gcontext); - return (GProtocolDecl) gpd.del(del); - } - - @Override - public ScribNode leaveRoleCollection(ScribNode parent, ScribNode child, RoleCollector coll, ScribNode visited) throws ScribbleException - { - GProtocolDecl gpd = (GProtocolDecl) visited; - - // Need to do here (e.g. RoleDeclList too early, def not visited yet) - // Currently only done for global, local does roledecl fixing after role collection -- should separate this check to a later pass after context building - // Maybe relax to check only occs.size() > 1 - List decls = gpd.header.roledecls.getRoles(); - Set occs = coll.getNames(); - if (occs.size() != decls.size()) - { - decls.removeAll(occs); - throw new ScribbleException(gpd.header.roledecls.getSource(), "Unused role decl(s) in " + gpd.header.name + ": " + decls); - } - - return super.leaveRoleCollection(parent, child, coll, gpd); - } - - @Override - public GProtocolDecl - leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) throws ScribbleException - { - AstFactory af = proj.job.af; - - Module root = proj.job.getContext().getModule(proj.getModuleContext().root); - GProtocolDecl gpd = (GProtocolDecl) visited; - GProtocolHeader gph = gpd.getHeader(); - Role self = proj.peekSelf(); - - LProtocolNameNode pn = Projector.makeProjectedSimpleNameNode(af, gph.getSource(), gph.getDeclName(), self); - RoleDeclList roledecls = gph.roledecls.project(af, self); - NonRoleParamDeclList paramdecls = gph.paramdecls.project(af, self); - //LProtocolHeader hdr = af.LProtocolHeader(gpd.header.getSource(), pn, roledecls, paramdecls); // FIXME: make a header del and move there? - LProtocolHeader hdr = gph.project(af, self, pn, roledecls, paramdecls); - LProtocolDef def = (LProtocolDef) ((ProjectionEnv) gpd.def.del().env()).getProjection(); - LProtocolDecl lpd = gpd.project(af, root, self, hdr, def); // FIXME: is root (always) the correct module? (wrt. LProjectionDeclDel?) - - Map> deps = ((GProtocolDeclDel) gpd.del()).getGlobalProtocolDependencies(self); - Module projected = ((ModuleDel) root.del()).createModuleForProjection(proj, root, gpd, lpd, deps); - proj.addProjection(gpd.getFullMemberName(root), self, projected); - return gpd; - } - - protected Map> getGlobalProtocolDependencies(Role self) - { - DependencyMap deps = getProtocolDeclContext().getDependencyMap(); - return deps.getDependencies().get(self); - } - - @Override - public void enterValidation(ScribNode parent, ScribNode child, GProtocolValidator checker) throws ScribbleException - { - GProtocolDecl gpd = (GProtocolDecl) child; - if (gpd.isAuxModifier()) - { - return; - } - - GProtocolName fullname = gpd.getFullMemberName((Module) parent); - validate(checker.job, fullname, true); - if (!checker.job.fair) - { - checker.job.debugPrintln("(" + fullname + ") Validating with \"unfair\" output choices.. "); - validate(checker.job, fullname, false); // FIXME: only need to check progress, not full validation - } - } - - private static void validate(Job job, GProtocolName fullname, boolean fair) throws ScribbleException - { - JobContext jc = job.getContext(); - SGraph graph = (fair) ? jc.getSGraph(fullname) : jc.getUnfairSGraph(fullname); - //graph.toModel().validate(job); - job.sf.newSModel(graph).validate(job); - } -} - diff --git a/scribble-core/src/main/java/org/scribble/del/global/GProtocolDefDel.java b/scribble-core/src/main/java/org/scribble/del/global/GProtocolDefDel.java deleted file mode 100644 index d9d2a84be..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GProtocolDefDel.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.ProtocolDef; -import org.scribble.ast.ScribNode; -import org.scribble.ast.global.GInteractionSeq; -import org.scribble.ast.global.GProtocolBlock; -import org.scribble.ast.global.GProtocolDecl; -import org.scribble.ast.global.GProtocolDef; -import org.scribble.ast.global.GRecursion; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.ast.local.LProtocolDef; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.del.ProtocolDefDel; -import org.scribble.del.ScribDelBase; -import org.scribble.main.ScribbleException; -import org.scribble.type.SubprotocolSig; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.kind.RecVarKind; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.Projector; -import org.scribble.visit.context.env.ProjectionEnv; -import org.scribble.visit.env.InlineProtocolEnv; - -public class GProtocolDefDel extends ProtocolDefDel -{ - public GProtocolDefDel() - { - - } - - @Override - protected GProtocolDefDel copy() - { - GProtocolDefDel copy = new GProtocolDefDel(); - copy.inlined = this.inlined; - return copy; - } - - @Override - public ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - CommonTree blame = ((GProtocolDecl) parent).header.getSource(); - SubprotocolSig subsig = inl.peekStack(); - GProtocolDef def = (GProtocolDef) visited; - GProtocolBlock block = (GProtocolBlock) ((InlineProtocolEnv) def.block.del().env()).getTranslation(); - RecVarNode recvar = (RecVarNode) inl.job.af.SimpleNameNode(blame, RecVarKind.KIND, inl.getSubprotocolRecVar(subsig).toString()); - GRecursion rec = inl.job.af.GRecursion(blame, recvar, block); - GInteractionSeq gis = inl.job.af.GInteractionSeq(blame, Arrays.asList(rec)); - GProtocolDef inlined = inl.job.af.GProtocolDef(def.getSource(), inl.job.af.GProtocolBlock(blame, gis)); - inl.pushEnv(inl.popEnv().setTranslation(inlined)); - GProtocolDefDel copy = setInlinedProtocolDef(inlined); - return (GProtocolDef) ScribDelBase.popAndSetVisitorEnv(this, inl, (GProtocolDef) def.del(copy)); - } - - @Override - public void enterProjection(ScribNode parent, ScribNode child, Projector proj) throws ScribbleException - { - //pushVisitorEnv(parent, child, proj); - ScribDelBase.pushVisitorEnv(this, proj); - } - - @Override - public GProtocolDef leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) throws ScribbleException - { - GProtocolDef gpd = (GProtocolDef) visited; - LProtocolBlock block = (LProtocolBlock) ((ProjectionEnv) gpd.block.del().env()).getProjection(); - LProtocolDef projection = gpd.project(proj.job.af, proj.peekSelf(), block); - proj.pushEnv(proj.popEnv().setProjection(projection)); - return (GProtocolDef) ScribDelBase.popAndSetVisitorEnv(this, proj, gpd); - } - - @Override - public GProtocolDef getInlinedProtocolDef() - { - return (GProtocolDef) super.getInlinedProtocolDef(); - } - - @Override - public GProtocolDefDel setInlinedProtocolDef(ProtocolDef inlined) - { - return (GProtocolDefDel) super.setInlinedProtocolDef(inlined); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GRecursionDel.java b/scribble-core/src/main/java/org/scribble/del/global/GRecursionDel.java deleted file mode 100644 index 19a1eb678..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GRecursionDel.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.GProtocolBlock; -import org.scribble.ast.global.GRecursion; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.ast.local.LRecursion; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.del.RecursionDel; -import org.scribble.main.ScribbleException; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.Projector; -import org.scribble.visit.context.env.ProjectionEnv; -import org.scribble.visit.env.InlineProtocolEnv; -import org.scribble.visit.wf.WFChoiceChecker; -import org.scribble.visit.wf.env.WFChoiceEnv; - -public class GRecursionDel extends RecursionDel implements GCompoundInteractionNodeDel -{ - @Override - public ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - GRecursion gr = (GRecursion) visited; - //RecVarNode recvar = gr.recvar.clone(); - RecVarNode recvar = (RecVarNode) ((InlineProtocolEnv) gr.recvar.del().env()).getTranslation(); - GProtocolBlock block = (GProtocolBlock) ((InlineProtocolEnv) gr.block.del().env()).getTranslation(); - GRecursion inlined = inl.job.af.GRecursion(gr.getSource(), recvar, block); - inl.pushEnv(inl.popEnv().setTranslation(inlined)); - return (GRecursion) super.leaveProtocolInlining(parent, child, inl, gr); - } - - @Override - public GRecursion leaveInlinedWFChoiceCheck(ScribNode parent, ScribNode child, WFChoiceChecker checker, ScribNode visited) throws ScribbleException - { - GRecursion rec = (GRecursion) visited; - WFChoiceEnv merged = checker.popEnv().mergeContext((WFChoiceEnv) rec.block.del().env()); // Merge block child env into current rec env - checker.pushEnv(merged); - return (GRecursion) super.leaveInlinedWFChoiceCheck(parent, child, checker, rec); // Will merge current rec env into parent (and set env on del) - } - - @Override - public GRecursion leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) throws ScribbleException - { - GRecursion gr = (GRecursion) visited; - LProtocolBlock block = - (LProtocolBlock) ((ProjectionEnv) gr.block.del().env()).getProjection(); - //((GProtocolBlockDel) gr.block.del()).project(gr.getBlock(), self); - LRecursion projection = gr.project(proj.job.af, proj.peekSelf(), block); - proj.pushEnv(proj.popEnv().setProjection(projection)); - return (GRecursion) GCompoundInteractionNodeDel.super.leaveProjection(parent, child, proj, gr); - } - - /*@Override - public void enterAnnotCheck(ScribNode parent, ScribNode child, AnnotationChecker checker) throws ScribbleException - { - ScribDelBase.pushVisitorEnv(this, checker); - } - - @Override - public GRecursion leaveAnnotCheck(ScribNode parent, ScribNode child, AnnotationChecker checker, ScribNode visited) throws ScribbleException - { - return (GRecursion) ScribDelBase.popAndSetVisitorEnv(this, checker, visited); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GSimpleInteractionNodeDel.java b/scribble-core/src/main/java/org/scribble/del/global/GSimpleInteractionNodeDel.java deleted file mode 100644 index 97621986e..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GSimpleInteractionNodeDel.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 GSimpleInteractionNodeDel extends GInteractionNodeDel -{ - -} diff --git a/scribble-core/src/main/java/org/scribble/del/global/GWrapDel.java b/scribble-core/src/main/java/org/scribble/del/global/GWrapDel.java deleted file mode 100644 index 7315fdb57..000000000 --- a/scribble-core/src/main/java/org/scribble/del/global/GWrapDel.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ast.local.LNode; -import org.scribble.del.ConnectionActionDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.Role; -import org.scribble.visit.context.Projector; -import org.scribble.visit.wf.NameDisambiguator; -import org.scribble.visit.wf.WFChoiceChecker; -import org.scribble.visit.wf.env.WFChoiceEnv; - -// FIXME: make WrapDel (cf., G/LMessageTransferDel) -public class GWrapDel extends ConnectionActionDel implements GSimpleInteractionNodeDel -{ - public GWrapDel() - { - - } - - @Override - public ScribNode leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - GWrap gw = (GWrap) visited; - /*Role src = gw.src.toName(); - Role dest = gw.dest.toName();*/ - return gw; - } - - @Override - public GWrap leaveInlinedWFChoiceCheck(ScribNode parent, ScribNode child, WFChoiceChecker checker, ScribNode visited) throws ScribbleException - { - GWrap gw = (GWrap) visited; - - Role src = gw.src.toName(); - Role dest = gw.dest.toName(); - if (!checker.peekEnv().isEnabled(src)) - { - throw new ScribbleException(gw.src.getSource(), "Role not enabled: " + src); - } - if (!checker.peekEnv().isEnabled(dest)) - { - throw new ScribbleException(gw.dest.getSource(), "Role not enabled: " + dest); - } - //Message msg = gw.msg.toMessage(); // Unit message - if (src.equals(dest)) - { - throw new ScribbleException(gw.getSource(), "[TODO] Self connections not supported: " + gw); - } - WFChoiceEnv env = checker.popEnv(); - if (!env.isConnected(src, dest)) - { - throw new ScribbleException(gw.getSource(), "Roles not (necessarily) connected: " + src + ", " + dest); - } - - //env = env.addMessage(src, dest, msg); - /*env = env - .connect(src, dest) - .addMessage(src, dest, new MessageSig(Op.EMPTY_OPERATOR, Payload.EMPTY_PAYLOAD));*/ - checker.pushEnv(env); - return gw; - } - - @Override - public ScribNode leaveProjection(ScribNode parent, ScribNode child, Projector proj, ScribNode visited) throws ScribbleException //throws ScribbleException - { - GWrap gw = (GWrap) visited; - Role self = proj.peekSelf(); - LNode projection = gw.project(proj.job.af, self); - proj.pushEnv(proj.popEnv().setProjection(projection)); - return (GWrap) GSimpleInteractionNodeDel.super.leaveProjection(parent, child, proj, gw); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LAcceptDel.java b/scribble-core/src/main/java/org/scribble/del/local/LAcceptDel.java deleted file mode 100644 index 1f25ba9da..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LAcceptDel.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ast.MessageSigNode; -import org.scribble.ast.ScribNode; -import org.scribble.ast.local.LAccept; -import org.scribble.main.ScribbleException; -import org.scribble.type.Payload; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; -import org.scribble.visit.context.EGraphBuilder; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; -import org.scribble.visit.context.UnguardedChoiceDoProjectionChecker; -import org.scribble.visit.context.env.UnguardedChoiceDoEnv; -import org.scribble.visit.wf.ExplicitCorrelationChecker; -import org.scribble.visit.wf.env.ExplicitCorrelationEnv; - -public class LAcceptDel extends LConnectionActionDel implements LSimpleInteractionNodeDel -{ - @Override - public LAccept leaveEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder builder, ScribNode visited) throws ScribbleException - { - LAccept la = (LAccept) visited; - Role peer = la.src.toName(); - MessageId mid = la.msg.toMessage().getId(); - Payload payload = la.msg.isMessageSigNode() // Hacky? - ? ((MessageSigNode) la.msg).payloads.toPayload() - : Payload.EMPTY_PAYLOAD; - builder.util.addEdge(builder.util.getEntry(), builder.job.ef.newEAccept(peer, mid, payload), builder.util.getExit()); - //builder.builder.addEdge(builder.builder.getEntry(), new Accept(peer), builder.builder.getExit()); - ////builder.builder.addEdge(builder.builder.getEntry(), Receive.get(peer, mid, payload), builder.builder.getExit()); - return (LAccept) super.leaveEGraphBuilding(parent, child, builder, la); - } - - @Override - public void enterProjectedChoiceSubjectFixing(ScribNode parent, ScribNode child, ProjectedChoiceSubjectFixer fixer) - { - fixer.setChoiceSubject(((LAccept) child).src.toName()); - } - - @Override - public void enterUnguardedChoiceDoProjectionCheck(ScribNode parent, ScribNode child, UnguardedChoiceDoProjectionChecker checker) throws ScribbleException - { - super.enterUnguardedChoiceDoProjectionCheck(parent, child, checker); - LAccept la = (LAccept) child; - UnguardedChoiceDoEnv env = checker.popEnv(); - env = env.setChoiceSubject(la.src.toName()); - checker.pushEnv(env); - } - - @Override - public LAccept leaveExplicitCorrelationCheck(ScribNode parent, ScribNode child, ExplicitCorrelationChecker checker, ScribNode visited) throws ScribbleException - { - LAccept la = (LAccept) visited; - ExplicitCorrelationEnv env = checker.popEnv(); - if (!env.canAccept()) - { - //throw new ScribbleException("Invalid accept action: " + la); - checker.job.warningPrintln("Session correlation warning for: " + la); - } - checker.pushEnv(env.disableAccept()); - return la; - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LChoiceDel.java b/scribble-core/src/main/java/org/scribble/del/local/LChoiceDel.java deleted file mode 100644 index 1af4d110b..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LChoiceDel.java +++ /dev/null @@ -1,167 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import org.scribble.ast.Choice; -import org.scribble.ast.ScribNode; -import org.scribble.ast.local.LChoice; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ChoiceDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.RoleKind; -import org.scribble.type.name.RecVar; -import org.scribble.type.name.Role; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.EGraphBuilder; -import org.scribble.visit.context.ProjectedChoiceDoPruner; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; -import org.scribble.visit.context.UnguardedChoiceDoProjectionChecker; -import org.scribble.visit.context.env.UnguardedChoiceDoEnv; -import org.scribble.visit.env.InlineProtocolEnv; -import org.scribble.visit.wf.ReachabilityChecker; -import org.scribble.visit.wf.env.ReachabilityEnv; - -public class LChoiceDel extends ChoiceDel implements LCompoundInteractionNodeDel -{ - /* // Not needed: just enters and pushes, done by base routine (only overwite if do extra stuff, like pushChoiceParent) - @Override - public void enterUnguardedChoiceDoProjectionCheck(ScribNode parent, ScribNode child, ChoiceUnguardedSubprotocolChecker checker) throws ScribbleException - { - ChoiceUnguardedSubprotocolEnv env = checker.peekEnv().enterContext(); - checker.pushEnv(env); - }*/ - - @Override - public ScribNode leaveUnguardedChoiceDoProjectionCheck(ScribNode parent, ScribNode child, UnguardedChoiceDoProjectionChecker checker, ScribNode visited) throws ScribbleException - { - 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 ScribbleException - { - 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 ScribbleException - { - 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 RuntimeScribbleException("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 ScribbleException(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; - } - - @Override - public ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - LChoice lc = (LChoice) visited; - List blocks = - lc.getBlocks().stream().map((b) -> (LProtocolBlock) ((InlineProtocolEnv) b.del().env()).getTranslation()).collect(Collectors.toList()); - RoleNode subj = lc.subj.clone(inl.job.af); - LChoice inlined = inl.job.af.LChoice(lc.getSource(), subj, blocks); - inl.pushEnv(inl.popEnv().setTranslation(inlined)); - return (LChoice) super.leaveProtocolInlining(parent, child, inl, lc); - } - - @Override - public LChoice leaveReachabilityCheck(ScribNode parent, ScribNode child, ReachabilityChecker checker, ScribNode visited) throws ScribbleException - { - LChoice cho = (LChoice) visited; - List benvs = - cho.getBlocks().stream().map((b) -> (ReachabilityEnv) b.del().env()).collect(Collectors.toList()); - ReachabilityEnv merged = checker.popEnv().mergeForChoice(benvs); - checker.pushEnv(merged); - return (LChoice) LCompoundInteractionNodeDel.super.leaveReachabilityCheck(parent, child, checker, visited); // records the current checker Env to the current del; also pops and merges that env into the parent env - } - - @Override - public void enterEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder graph) - { - super.enterEGraphBuilding(parent, child, graph); - graph.util.enterChoice(); - } - - public LChoice visitForFsmConversion(EGraphBuilder graph, LChoice child) - { - try - { - for (LProtocolBlock block : child.getBlocks()) - { - graph.util.pushChoiceBlock(); - block.accept(graph); - graph.util.popChoiceBlock(); - } - } - catch (ScribbleException e) - { - throw new RuntimeException("Shouldn't get in here: " + e); - } - return child; - } - - @Override - public ScribNode leaveEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder graph, ScribNode visited) throws ScribbleException - { - graph.util.leaveChoice(); - return super.leaveEGraphBuilding(parent, child, graph, visited); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LCompoundInteractionNodeDel.java b/scribble-core/src/main/java/org/scribble/del/local/LCompoundInteractionNodeDel.java deleted file mode 100644 index e6c263cd3..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LCompoundInteractionNodeDel.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ast.ScribNode; -import org.scribble.ast.local.LCompoundInteractionNode; -import org.scribble.main.ScribbleException; -import org.scribble.visit.wf.ReachabilityChecker; -import org.scribble.visit.wf.env.ReachabilityEnv; - -public interface LCompoundInteractionNodeDel extends LInteractionNodeDel -{ - @Override - default LCompoundInteractionNode leaveReachabilityCheck(ScribNode parent, ScribNode child, ReachabilityChecker checker, ScribNode visited) throws ScribbleException - { - // Following CompoundInteractionNodeDel#leaveInlinedProtocolUnfolding/leaveWFChoiceCheck - ReachabilityEnv visited_env = checker.popEnv(); - setEnv(visited_env); - ReachabilityEnv parent_env = checker.popEnv(); - parent_env = parent_env.mergeContext(visited_env); - checker.pushEnv(parent_env); - return (LCompoundInteractionNode) visited; - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LConnectionActionDel.java b/scribble-core/src/main/java/org/scribble/del/local/LConnectionActionDel.java deleted file mode 100644 index 1fcc2e7d3..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LConnectionActionDel.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ast.ScribNode; -import org.scribble.ast.local.LConnectionAction; -import org.scribble.del.ConnectionActionDel; -import org.scribble.main.ScribbleException; -import org.scribble.visit.wf.ExplicitCorrelationChecker; - -public abstract class LConnectionActionDel extends ConnectionActionDel implements LSimpleInteractionNodeDel -{ - @Override - public LConnectionAction leaveExplicitCorrelationCheck(ScribNode parent, ScribNode child, ExplicitCorrelationChecker checker, ScribNode visited) throws ScribbleException - { - LConnectionAction lca = (LConnectionAction) visited; - checker.pushEnv(checker.popEnv().disableAccept()); - return lca; - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LContinueDel.java b/scribble-core/src/main/java/org/scribble/del/local/LContinueDel.java deleted file mode 100644 index 9fc081899..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LContinueDel.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.scribble.ast.ScribNode; -import org.scribble.ast.local.LContinue; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.del.ContinueDel; -import org.scribble.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.name.RecVar; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.EGraphBuilder; -import org.scribble.visit.env.InlineProtocolEnv; -import org.scribble.visit.wf.ReachabilityChecker; -import org.scribble.visit.wf.env.ReachabilityEnv; - -public class LContinueDel extends ContinueDel implements LSimpleInteractionNodeDel -{ - @Override - public LContinue leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - LContinue lc = (LContinue) visited; - RecVarNode recvar = (RecVarNode) ((InlineProtocolEnv) lc.recvar.del().env()).getTranslation(); - LContinue inlined = inl.job.af.LContinue(lc.getSource(), recvar); - inl.pushEnv(inl.popEnv().setTranslation(inlined)); - return (LContinue) super.leaveProtocolInlining(parent, child, inl, lc); - } - - @Override - public LContinue leaveReachabilityCheck(ScribNode parent, ScribNode child, ReachabilityChecker checker, ScribNode visited) throws ScribbleException - { - // "Entering" the continue here in leave, where we can merge the new state into the parent Env - // Generally: if side effecting Env state to be merged into the parent (not just popped and discarded), leave must be overridden to do so - LContinue lc = (LContinue) visited; - ReachabilityEnv env = checker.popEnv().addContinueLabel(lc.recvar.toName()); - setEnv(env); // Env recording probably not needed for all LocalInteractionNodes, just the compound ones, like for WF-choice checking - checker.pushEnv(checker.popEnv().mergeContext(env)); - return lc; - } - - @Override - public LContinue leaveEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder graph, ScribNode visited) throws ScribbleException - { - LContinue lr = (LContinue) visited; - RecVar rv = lr.recvar.toName(); - if (graph.util.isUnguardedInChoice()) - { - graph.util.addContinueEdge(graph.util.getEntry(), rv); - } - else - { - // ** "Overwrites" previous edge built by send/receive(s) leading to this continue - Iterator preds = graph.util.getPredecessors().iterator(); - Iterator prevs = graph.util.getPreviousActions().iterator(); - EState entry = graph.util.getEntry(); - - Set> removed = new HashSet<>(); - // HACK: for identical edges, i.e. same pred/prev/succ (e.g. rec X { choice at A { A->B:1 } or { A->B:1 } continue X; }) // FIXME: do here, or refactor into GraphBuilder? - // Because duplicate edges preemptively pruned by ModelState.addEdge, but corresponding predecessors not pruned // FIXME: make uniform - while (preds.hasNext()) - { - EState pred = preds.next(); - EAction prev = prevs.next(); - List tmp = Arrays.asList(pred, prev, entry); - if (!removed.contains(tmp)) - { - removed.add(tmp); - graph.util.removeEdgeFromPredecessor(pred, prev); // Assumes pred is a predecessor, and removes pred from current predecessors.. - } - graph.util.addRecursionEdge(pred, prev, graph.util.getRecursionEntry(rv)); // May be repeated for non-det, but OK // Combine with removeEdgeFromPredecessor? - } - } - return (LContinue) super.leaveEGraphBuilding(parent, child, graph, lr); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LDoDel.java b/scribble-core/src/main/java/org/scribble/del/local/LDoDel.java deleted file mode 100644 index 38d4708b2..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LDoDel.java +++ /dev/null @@ -1,151 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 java.util.Iterator; -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.ast.RoleArg; -import org.scribble.ast.RoleArgList; -import org.scribble.ast.ScribNode; -import org.scribble.ast.global.GProtocolDecl; -import org.scribble.ast.local.LContinue; -import org.scribble.ast.local.LDo; -import org.scribble.ast.local.LInteractionSeq; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.ast.local.LProtocolDecl; -import org.scribble.ast.local.LRecursion; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.del.DoDel; -import org.scribble.main.JobContext; -import org.scribble.main.ScribbleException; -import org.scribble.type.SubprotocolSig; -import org.scribble.type.kind.RecVarKind; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.LProtocolName; -import org.scribble.type.name.ProtocolName; -import org.scribble.type.name.Role; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.ProjectedRoleDeclFixer; -import org.scribble.visit.context.ProtocolDeclContextBuilder; -import org.scribble.visit.context.UnguardedChoiceDoProjectionChecker; -import org.scribble.visit.env.InlineProtocolEnv; - -public class LDoDel extends DoDel implements LSimpleInteractionNodeDel -{ - // Part of context building - @Override - protected void addProtocolDependency(ProtocolDeclContextBuilder builder, Role self, ProtocolName proto, Role target) - { - builder.addLocalProtocolDependency(self, (LProtocolName) proto, target); - } - - // Only called if cycle - public LDo visitForSubprotocolInlining(ProtocolDefInliner builder, LDo child) - { - CommonTree blame = child.getSource(); // Cf., GDoDel - SubprotocolSig subsig = builder.peekStack(); - RecVarNode recvar = (RecVarNode) builder.job.af.SimpleNameNode(blame, - RecVarKind.KIND, builder.getSubprotocolRecVar(subsig).toString()); - LContinue inlined = builder.job.af.LContinue(blame, recvar); - builder.pushEnv(builder.popEnv().setTranslation(inlined)); - return child; - } - - @Override - public LDo leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner dinlr, ScribNode visited) throws ScribbleException - { - if (!dinlr.isCycle()) - { - CommonTree blame = visited.getSource(); // Cf., GDoDel - SubprotocolSig subsig = dinlr.peekStack(); - RecVarNode recvar = (RecVarNode) dinlr.job.af.SimpleNameNode(blame, RecVarKind.KIND, dinlr.getSubprotocolRecVar(subsig).toString()); - LInteractionSeq gis = (LInteractionSeq) (((InlineProtocolEnv) dinlr.peekEnv()).getTranslation()); - LProtocolBlock gb = dinlr.job.af.LProtocolBlock(blame, gis); - LRecursion inlined = dinlr.job.af.LRecursion(blame, recvar, gb); - dinlr.pushEnv(dinlr.popEnv().setTranslation(inlined)); - dinlr.removeSubprotocolRecVar(subsig); - } - return (LDo) super.leaveProtocolInlining(parent, child, dinlr, visited); - } - - // 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 ScribbleException - { - JobContext jc = fixer.job.getContext(); - LDo ld = (LDo) visited; - LProtocolDecl lpd = ld.getTargetProtocolDecl(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 - GProtocolName source = ((LProjectionDeclDel) lpd.del()).getSourceProtocol(); - GProtocolDecl gpd = (GProtocolDecl) jc.getModule(source.getPrefix()).getProtocolDecl(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 = ((LProtocolDeclDel) lpd.del()).getProtocolDeclContext().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.getProtocolNameNode())); - } - - @Override - public ScribNode leaveUnguardedChoiceDoProjectionCheck(ScribNode parent, ScribNode child, UnguardedChoiceDoProjectionChecker checker, ScribNode visited) throws ScribbleException - { - /*//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-core/src/main/java/org/scribble/del/local/LInteractionNodeDel.java b/scribble-core/src/main/java/org/scribble/del/local/LInteractionNodeDel.java deleted file mode 100644 index ee5b965ba..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LInteractionNodeDel.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ast.ScribNode; -import org.scribble.ast.local.LInteractionNode; -import org.scribble.del.InteractionNodeDel; -import org.scribble.del.ScribDelBase; -import org.scribble.main.ScribbleException; -import org.scribble.visit.wf.ReachabilityChecker; - -public interface LInteractionNodeDel extends InteractionNodeDel -{ - // Unlike WF-choice enter/leave for CompoundInteractionNodeDelegate (i.e. both global/local), reachability is limited to local only - @Override - default void enterReachabilityCheck(ScribNode parent, ScribNode child, ReachabilityChecker checker) throws ScribbleException - { - ScribDelBase.pushVisitorEnv(this, checker); - } - - @Override - default LInteractionNode leaveReachabilityCheck(ScribNode parent, ScribNode child, ReachabilityChecker checker, ScribNode visited) throws ScribbleException - { - return (LInteractionNode) ScribDelBase.popAndSetVisitorEnv(this, checker, visited); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LInteractionSeqDel.java b/scribble-core/src/main/java/org/scribble/del/local/LInteractionSeqDel.java deleted file mode 100644 index f0692a300..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LInteractionSeqDel.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.scribble.ast.InteractionNode; -import org.scribble.ast.ScribNode; -import org.scribble.ast.local.LInteractionNode; -import org.scribble.ast.local.LInteractionSeq; -import org.scribble.ast.local.LRecursion; -import org.scribble.del.InteractionSeqDel; -import org.scribble.del.ScribDelBase; -import org.scribble.main.ScribbleException; -import org.scribble.model.endpoint.EState; -import org.scribble.type.kind.Local; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.EGraphBuilder; -import org.scribble.visit.context.ProjectedChoiceDoPruner; -import org.scribble.visit.context.RecRemover; -import org.scribble.visit.env.InlineProtocolEnv; -import org.scribble.visit.wf.ReachabilityChecker; -import org.scribble.visit.wf.env.ReachabilityEnv; - -public class LInteractionSeqDel extends InteractionSeqDel -{ - @Override - public ScribNode leaveProjectedChoiceDoPruning(ScribNode parent, ScribNode child, ProjectedChoiceDoPruner pruner, ScribNode visited) throws ScribbleException - { - LInteractionSeq lc = (LInteractionSeq) visited; - List actions = lc.getInteractions().stream().filter((li) -> li != null).collect(Collectors.toList()); - return lc.reconstruct(actions); - } - - // enter in super - @Override - public ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - LInteractionSeq lis = (LInteractionSeq) visited; - List lins = new LinkedList(); - for (LInteractionNode li : lis.getInteractions()) - { - ScribNode inlined = ((InlineProtocolEnv) li.del().env()).getTranslation(); - if (inlined instanceof LInteractionSeq) - { - lins.addAll(((LInteractionSeq) inlined).getInteractions()); - } - else - { - lins.add((LInteractionNode) inlined); - } - } - LInteractionSeq inlined = inl.job.af.LInteractionSeq(lis.getSource(), lins); - inl.pushEnv(inl.popEnv().setTranslation(inlined)); - return (LInteractionSeq) ScribDelBase.popAndSetVisitorEnv(this, inl, lis); - } - - // Replaces visitChildrenInSubprotocols for LocalInteractionSequence - public LInteractionSeq visitForReachabilityChecking(ReachabilityChecker checker, LInteractionSeq child) throws ScribbleException - { - List visited = new LinkedList<>(); - for (InteractionNode li : child.getInteractions()) - { - ReachabilityEnv re = checker.peekEnv(); - if (!re.isSequenceable()) - { - throw new ScribbleException(li.getSource(), "Invalid/unreachable sequence to: " + li); - } - visited.add((LInteractionNode) li.accept(checker)); - } - return child; - } - - public LInteractionSeq visitForFsmConversion(EGraphBuilder conv, LInteractionSeq child) throws ScribbleException - { - EState entry = conv.util.getEntry(); - EState exit = conv.util.getExit(); - //try - { - /*for (int i = child.getInteractions().size() - 1; i >= 0; i--) // Backwards for "tau-less" continue - { - if (i > 0) - { - EndpointState tmp = conv.builder.newState(Collections.emptySet()); - conv.builder.setEntry(tmp); - child.getInteractions().get(i).accept(conv); - conv.builder.setExit(conv.builder.getEntry()); // entry may not be tmp, entry/exit can be modified, e.g. continue - } - else - { - conv.builder.setEntry(entry); - child.getInteractions().get(i).accept(conv); - } - }*/ - for (int i = 0; i < child.getInteractions().size(); i++) - { - if (i == child.getInteractions().size() - 1) - { - conv.util.setExit(exit); - child.getInteractions().get(i).accept(conv); - } - else - { - EState tmp = //conv.util.newState(Collections.emptySet()); - conv.util.ef.newEState(Collections.emptySet()); - conv.util.setExit(tmp); - child.getInteractions().get(i).accept(conv); - conv.util.setEntry(conv.util.getExit()); // exit may not be tmp, entry/exit can be modified, e.g. continue - } - } - } - /*catch (ScribbleException e) // Hack: EFSM building now done before reachability check, removeEdge can fail - { - throw new RuntimeException("Shouldn't get in here: " + e); - }*/ - //conv.builder.setExit(exit); - conv.util.setEntry(entry); - return child; - } - - // Duplicated from GInteractionSeq - @Override - public LInteractionSeq leaveRecRemoval(ScribNode parent, ScribNode child, RecRemover rem, ScribNode visited) - throws ScribbleException - { - 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-core/src/main/java/org/scribble/del/local/LMessageTransferDel.java b/scribble-core/src/main/java/org/scribble/del/local/LMessageTransferDel.java deleted file mode 100644 index ad26def9f..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LMessageTransferDel.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ast.ScribNode; -import org.scribble.ast.local.LMessageTransfer; -import org.scribble.del.MessageTransferDel; -import org.scribble.main.ScribbleException; -import org.scribble.visit.wf.ExplicitCorrelationChecker; - -public abstract class LMessageTransferDel extends MessageTransferDel implements LSimpleInteractionNodeDel -{ - @Override - public ScribNode leaveExplicitCorrelationCheck(ScribNode parent, ScribNode child, ExplicitCorrelationChecker checker, ScribNode visited) throws ScribbleException - { - LMessageTransfer lmt = (LMessageTransfer) visited; - checker.pushEnv(checker.popEnv().disableAccept()); - return lmt; - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LParallelDel.java b/scribble-core/src/main/java/org/scribble/del/local/LParallelDel.java deleted file mode 100644 index c6ef195c5..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LParallelDel.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ParallelDel; - -public class LParallelDel extends ParallelDel implements LCompoundInteractionNodeDel -{ - -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LProjectionDeclDel.java b/scribble-core/src/main/java/org/scribble/del/local/LProjectionDeclDel.java deleted file mode 100644 index ec0e46885..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LProjectionDeclDel.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import org.scribble.ast.RoleDecl; -import org.scribble.ast.RoleDeclList; -import org.scribble.ast.ScribNode; -import org.scribble.ast.local.LProtocolDecl; -import org.scribble.ast.local.LProtocolHeader; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.Role; -import org.scribble.visit.context.ProjectedRoleDeclFixer; - -public class LProjectionDeclDel extends LProtocolDeclDel -{ - // Maybe better to store in context, but more convenient to pass to here via factory (than infer in context building) -- could alternatively store in projected module - protected final GProtocolName fullname; - protected final Role self; // Can be obtained from LProtocolHeader? - - public LProjectionDeclDel(GProtocolName fullname, Role self) - { - this.fullname = fullname; - this.self = self; - } - - @Override - protected LProtocolDeclDel copy() - { - return new LProjectionDeclDel(this.fullname, this.self); - } - - @Override - public ScribNode leaveProjectedRoleDeclFixing(ScribNode parent, ScribNode child, ProjectedRoleDeclFixer fixer, ScribNode visited) throws ScribbleException - { - LProtocolDecl lpd = (LProtocolDecl) visited; - // FIXME: ensure all role params are used, to avoid empty roledecllist - Set occs = ((LProtocolDeclDel) lpd.del()).getProtocolDeclContext().getRoleOccurrences(); - List rds = lpd.header.roledecls.getDecls().stream().filter((rd) -> - occs.contains(rd.getDeclName())).collect(Collectors.toList()); - RoleDeclList rdl = fixer.job.af.RoleDeclList(lpd.header.roledecls.getSource(), rds); - LProtocolHeader tmp = lpd.getHeader(); - LProtocolHeader hdr = tmp.reconstruct(tmp.getNameNode(), rdl, tmp.paramdecls); - LProtocolDecl fixed = lpd.reconstruct(hdr, lpd.def); - - fixer.job.debugPrintln("\n[DEBUG] Projected " + getSourceProtocol() + " for " + getSelfRole() + ":\n" + fixed); - - return super.leaveProjectedRoleDeclFixing(parent, child, fixer, fixed); - } - - public GProtocolName getSourceProtocol() - { - return this.fullname; - } - - // Redundant with SelfRoleDecl in header - public Role getSelfRole() - { - return this.self; - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LProtocolBlockDel.java b/scribble-core/src/main/java/org/scribble/del/local/LProtocolBlockDel.java deleted file mode 100644 index 10df42053..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LProtocolBlockDel.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ast.ScribNode; -import org.scribble.ast.local.LInteractionSeq; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.del.ProtocolBlockDel; -import org.scribble.del.ScribDelBase; -import org.scribble.main.ScribbleException; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.env.InlineProtocolEnv; -import org.scribble.visit.wf.ReachabilityChecker; - -public class LProtocolBlockDel extends ProtocolBlockDel -{ - @Override - public ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - LProtocolBlock lpb = (LProtocolBlock) visited; - LInteractionSeq seq = (LInteractionSeq) ((InlineProtocolEnv) lpb.seq.del().env()).getTranslation(); - LProtocolBlock inlined = inl.job.af.LProtocolBlock(lpb.getSource(), seq); - inl.pushEnv(inl.popEnv().setTranslation(inlined)); - return (LProtocolBlock) ScribDelBase.popAndSetVisitorEnv(this, inl, lpb); - } - - @Override - public void enterReachabilityCheck(ScribNode parent, ScribNode child, ReachabilityChecker checker) throws ScribbleException - { - ScribDelBase.pushVisitorEnv(this, checker); - } - - @Override - public LProtocolBlock leaveReachabilityCheck(ScribNode parent, ScribNode child, ReachabilityChecker checker, ScribNode visited) throws ScribbleException - { - return (LProtocolBlock) ScribDelBase.popAndSetVisitorEnv(this, checker, visited); // records the current checker Env to the current del; also pops and merges that env into the parent env - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LProtocolDeclDel.java b/scribble-core/src/main/java/org/scribble/del/local/LProtocolDeclDel.java deleted file mode 100644 index d619c4553..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LProtocolDeclDel.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 java.util.Collections; - -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.local.LProtocolDeclContext; -import org.scribble.ast.local.LProtocolDecl; -import org.scribble.del.ProtocolDeclDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.Local; -import org.scribble.type.name.LProtocolName; -import org.scribble.type.name.ProtocolName; -import org.scribble.type.name.Role; -import org.scribble.visit.context.EGraphBuilder; -import org.scribble.visit.context.ProtocolDeclContextBuilder; - -public class LProtocolDeclDel extends ProtocolDeclDel -{ - public LProtocolDeclDel() - { - - } - - @Override - protected LProtocolDeclDel copy() - { - return new LProtocolDeclDel(); - } - - @Override - protected void addSelfDependency(ProtocolDeclContextBuilder builder, ProtocolName proto, Role role) - { - builder.addLocalProtocolDependency(role, (LProtocolName) proto, role); - } - - @Override - public void enterProtocolDeclContextBuilding(ScribNode parent, ScribNode child, ProtocolDeclContextBuilder builder) throws ScribbleException - { - super.enterProtocolDeclContextBuilding(parent, child, builder); - } - - @Override - public LProtocolDecl leaveProtocolDeclContextBuilding(ScribNode parent, ScribNode child, ProtocolDeclContextBuilder builder, ScribNode visited) throws ScribbleException - { - LProtocolDecl lpd = (LProtocolDecl) visited; - LProtocolDeclContext lcontext = new LProtocolDeclContext(builder.getLocalProtocolDependencyMap()); - LProtocolDeclDel del = (LProtocolDeclDel) setProtocolDeclContext(lcontext); - return (LProtocolDecl) lpd.del(del); - } - - @Override - public void enterEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder builder) - { - builder.util.init(builder.job.ef.newEState(Collections.emptySet())); // Same util is used for multiple protos, need to (re-)init each time - } - - @Override - public ScribNode leaveEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder graph, ScribNode visited) - { - /*LProtocolDecl lpd = (LProtocolDecl) visited; // Refactored into JobContext - - JobContext jc = graph.getJobContext(); - // FIXME: should just bypass builder visit if already built - LProtocolName lpn = lpd.getFullMemberName((Module) parent); - if (jc.getEndpointGraph(lpn) == null) // FIXME: what is the routine to obtain gpn from lpn? - { - //EndpointGraph fsm = new EndpointGraph(graph.builder.getEntry(), graph.builder.getExit()); - EndpointGraph graph = graph.builder.finalise(); - - jc.addEndpointGraph(lpn, graph); - }*/ - return visited; - } - - @Override - public LProtocolDeclContext getProtocolDeclContext() - { - return (LProtocolDeclContext) super.getProtocolDeclContext(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LProtocolDefDel.java b/scribble-core/src/main/java/org/scribble/del/local/LProtocolDefDel.java deleted file mode 100644 index 623b48ffd..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LProtocolDefDel.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 java.util.Arrays; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.ProtocolDef; -import org.scribble.ast.ScribNode; -import org.scribble.ast.local.LInteractionSeq; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.ast.local.LProtocolDecl; -import org.scribble.ast.local.LProtocolDef; -import org.scribble.ast.local.LRecursion; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.del.ProtocolDefDel; -import org.scribble.del.ScribDelBase; -import org.scribble.main.ScribbleException; -import org.scribble.type.SubprotocolSig; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.kind.RecVarKind; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.env.InlineProtocolEnv; - -public class LProtocolDefDel extends ProtocolDefDel -{ - public LProtocolDefDel() - { - - } - - @Override - protected LProtocolDefDel copy() - { - LProtocolDefDel copy = new LProtocolDefDel(); - copy.inlined = this.inlined; - return copy; - } - - @Override - public ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - CommonTree blame = ((LProtocolDecl) parent).header.getSource(); // Cf., GProtocolDefDel - SubprotocolSig subsig = inl.peekStack(); - LProtocolDef def = (LProtocolDef) visited; - LProtocolBlock block = (LProtocolBlock) ((InlineProtocolEnv) def.block.del().env()).getTranslation(); - RecVarNode recvar = (RecVarNode) inl.job.af.SimpleNameNode(blame, // The parent do would probably be the better source for blame - RecVarKind.KIND, inl.getSubprotocolRecVar(subsig).toString()); - LRecursion rec = inl.job.af.LRecursion(blame, recvar, block); - LInteractionSeq lis = inl.job.af.LInteractionSeq(blame, Arrays.asList(rec)); - LProtocolDef inlined = inl.job.af.LProtocolDef(def.getSource(), inl.job.af.LProtocolBlock(blame, lis)); - inl.pushEnv(inl.popEnv().setTranslation(inlined)); - LProtocolDefDel copy = setInlinedProtocolDef(inlined); - return (LProtocolDef) ScribDelBase.popAndSetVisitorEnv(this, inl, (LProtocolDef) def.del(copy)); - } - - @Override - public LProtocolDef getInlinedProtocolDef() - { - return (LProtocolDef) super.getInlinedProtocolDef(); - } - - @Override - public LProtocolDefDel setInlinedProtocolDef(ProtocolDef inlined) - { - return (LProtocolDefDel) super.setInlinedProtocolDef(inlined); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LReceiveDel.java b/scribble-core/src/main/java/org/scribble/del/local/LReceiveDel.java deleted file mode 100644 index 801b8510b..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LReceiveDel.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ast.MessageSigNode; -import org.scribble.ast.ScribNode; -import org.scribble.ast.local.LReceive; -import org.scribble.main.ScribbleException; -import org.scribble.type.Payload; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; -import org.scribble.visit.context.EGraphBuilder; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; -import org.scribble.visit.context.UnguardedChoiceDoProjectionChecker; -import org.scribble.visit.context.env.UnguardedChoiceDoEnv; - -public class LReceiveDel extends LMessageTransferDel -{ - @Override - public ScribNode leaveEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder builder, ScribNode visited) throws ScribbleException - { - LReceive lr = (LReceive) visited; - Role peer = lr.src.toName(); - MessageId mid = lr.msg.toMessage().getId(); - Payload payload = (lr.msg.isMessageSigNode()) // Hacky? - ? ((MessageSigNode) lr.msg).payloads.toPayload() - : Payload.EMPTY_PAYLOAD; - builder.util.addEdge(builder.util.getEntry(), builder.job.ef.newEReceive(peer, mid, payload), builder.util.getExit()); - //builder.builder.addEdge(builder.builder.getEntry(), Receive.get(peer, mid, payload), builder.builder.getExit()); - return (LReceive) super.leaveEGraphBuilding(parent, child, builder, lr); - } - - @Override - public void enterProjectedChoiceSubjectFixing(ScribNode parent, ScribNode child, ProjectedChoiceSubjectFixer fixer) - { - fixer.setChoiceSubject(((LReceive) child).src.toName()); - } - - @Override - public void enterUnguardedChoiceDoProjectionCheck(ScribNode parent, ScribNode child, UnguardedChoiceDoProjectionChecker checker) throws ScribbleException - { - super.enterUnguardedChoiceDoProjectionCheck(parent, child, checker); - LReceive lr = (LReceive) child; - UnguardedChoiceDoEnv env = checker.popEnv(); - env = env.setChoiceSubject(lr.src.toName()); - checker.pushEnv(env); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LRecursionDel.java b/scribble-core/src/main/java/org/scribble/del/local/LRecursionDel.java deleted file mode 100644 index 672744be9..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LRecursionDel.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ast.Recursion; -import org.scribble.ast.ScribNode; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.ast.local.LRecursion; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.del.RecursionDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.RecVar; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.EGraphBuilder; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; -import org.scribble.visit.context.UnguardedChoiceDoProjectionChecker; -import org.scribble.visit.context.env.UnguardedChoiceDoEnv; -import org.scribble.visit.env.InlineProtocolEnv; -import org.scribble.visit.wf.ReachabilityChecker; -import org.scribble.visit.wf.env.ReachabilityEnv; - -public class LRecursionDel extends RecursionDel implements LCompoundInteractionNodeDel -{ - @Override - public ScribNode leaveUnguardedChoiceDoProjectionCheck(ScribNode parent, ScribNode child, UnguardedChoiceDoProjectionChecker checker, ScribNode visited) throws ScribbleException - { - Recursion rec = (Recursion) visited; - UnguardedChoiceDoEnv merged = checker.popEnv().mergeContext((UnguardedChoiceDoEnv) rec.block.del().env()); - checker.pushEnv(merged); - return (Recursion) super.leaveUnguardedChoiceDoProjectionCheck(parent, child, checker, rec); - } - - @Override - public ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inl, ScribNode visited) throws ScribbleException - { - LRecursion lr = (LRecursion) visited; - //RecVarNode recvar = lr.recvar.clone(); - RecVarNode recvar = (RecVarNode) ((InlineProtocolEnv) lr.recvar.del().env()).getTranslation(); - LProtocolBlock block = (LProtocolBlock) ((InlineProtocolEnv) lr.block.del().env()).getTranslation(); - LRecursion inlined = inl.job.af.LRecursion(lr.getSource(), recvar, block); - inl.pushEnv(inl.popEnv().setTranslation(inlined)); - return (LRecursion) super.leaveProtocolInlining(parent, child, inl, lr); - } - - @Override - public LRecursion leaveReachabilityCheck(ScribNode parent, ScribNode child, ReachabilityChecker checker, ScribNode visited) throws ScribbleException - { - LRecursion lr = (LRecursion) visited; - ReachabilityEnv env = checker.popEnv().mergeContext((ReachabilityEnv) lr.block.del().env()); - env = env.removeContinueLabel(lr.recvar.toName()); - checker.pushEnv(env); - return (LRecursion) LCompoundInteractionNodeDel.super.leaveReachabilityCheck(parent, child, checker, visited); // records the current checker Env to the current del; also pops and merges that env into the parent env - } - - @Override - public void enterEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder graph) - { - super.enterEGraphBuilding(parent, child, graph); - LRecursion lr = (LRecursion) child; - RecVar rv = lr.recvar.toName(); - // Update existing state, not replace it -- cf. LDoDel - /*if (graph.builder.isUnguardedInChoice()) // Actually, not needed since unfoldings are enough to make graph building work (and this makes combined unguarded choice-rec and continue protocols work) - { - // Using "previous" entry for this rec lab works because unguarded recs already unfolded (including nested recvar shadowing -- if unguarded choice-rec, it will be unfolded and rec entry recorded for guarded unfolding) - graph.builder.pushRecursionEntry(rv, graph.builder.getRecursionEntry(rv)); - } - else*/ - { - graph.util.addEntryLabel(rv); - graph.util.pushRecursionEntry(rv, graph.util.getEntry()); - } - } - - @Override - public LRecursion leaveEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder graph, ScribNode visited) throws ScribbleException - { - LRecursion lr = (LRecursion) visited; - RecVar rv = lr.recvar.toName(); - graph.util.popRecursionEntry(rv); - return (LRecursion) super.leaveEGraphBuilding(parent, child, graph, lr); - } - - @Override - public void enterProjectedChoiceSubjectFixing(ScribNode parent, ScribNode child, ProjectedChoiceSubjectFixer fixer) - { - fixer.pushRec(((LRecursion) child).recvar.toName()); - } - - @Override - public ScribNode leaveProjectedChoiceSubjectFixing(ScribNode parent, ScribNode child, ProjectedChoiceSubjectFixer fixer, ScribNode visited) - { - fixer.popRec(((LRecursion) child).recvar.toName()); - return visited; - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LRequestDel.java b/scribble-core/src/main/java/org/scribble/del/local/LRequestDel.java deleted file mode 100644 index b4f49ad9c..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LRequestDel.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ast.MessageSigNode; -import org.scribble.ast.ScribNode; -import org.scribble.ast.local.LRequest; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.Payload; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; -import org.scribble.visit.context.EGraphBuilder; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -public class LRequestDel extends LConnectionActionDel implements LSimpleInteractionNodeDel -{ - @Override - public LRequest leaveEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder builder, ScribNode visited) throws ScribbleException - { - LRequest lc = (LRequest) visited; - RoleNode dest = lc.dest; - Role peer = dest.toName(); - MessageId mid = lc.msg.toMessage().getId(); - Payload payload = lc.msg.isMessageSigNode() // Hacky? - ? ((MessageSigNode) lc.msg).payloads.toPayload() - : Payload.EMPTY_PAYLOAD; - builder.util.addEdge(builder.util.getEntry(), builder.job.ef.newERequest(peer, mid, payload), builder.util.getExit()); - //graph.builder.addEdge(graph.builder.getEntry(), new Connect(peer), graph.builder.getExit()); - ////builder.builder.addEdge(builder.builder.getEntry(), Send.get(peer, mid, payload), builder.builder.getExit()); - return (LRequest) super.leaveEGraphBuilding(parent, child, builder, lc); - } - - @Override - public void enterProjectedChoiceSubjectFixing(ScribNode parent, ScribNode child, ProjectedChoiceSubjectFixer fixer) - { - fixer.setChoiceSubject(((LRequest) child).src.toName()); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LSendDel.java b/scribble-core/src/main/java/org/scribble/del/local/LSendDel.java deleted file mode 100644 index 9433e1a56..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LSendDel.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 java.util.List; - -import org.scribble.ast.MessageSigNode; -import org.scribble.ast.ScribNode; -import org.scribble.ast.local.LMessageTransfer; -import org.scribble.ast.local.LSend; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.main.ScribbleException; -import org.scribble.type.Payload; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; -import org.scribble.visit.context.EGraphBuilder; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; -import org.scribble.visit.wf.ExplicitCorrelationChecker; - -public class LSendDel extends LMessageTransferDel -{ - - @Override - public ScribNode leaveEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder builder, ScribNode visited) throws ScribbleException - { - LSend ls = (LSend) visited; - List dests = ls.getDestinations(); - if (dests.size() > 1) - { - throw new ScribbleException("[TODO] EFSM building for multicast not supported: " + ls); - } - Role peer = dests.get(0).toName(); - MessageId mid = ls.msg.toMessage().getId(); - Payload payload = ls.msg.isMessageSigNode() // Hacky? - ? ((MessageSigNode) ls.msg).payloads.toPayload() - : Payload.EMPTY_PAYLOAD; - builder.util.addEdge(builder.util.getEntry(), builder.job.ef.newESend(peer, mid, payload), builder.util.getExit()); - //builder.builder.addEdge(builder.builder.getEntry(), Send.get(peer, mid, payload), builder.builder.getExit()); - return (LSend) super.leaveEGraphBuilding(parent, child, builder, ls); - } - - // Could make a LMessageTransferDel to factor this out with LReceiveDel - @Override - public void enterProjectedChoiceSubjectFixing(ScribNode parent, ScribNode child, ProjectedChoiceSubjectFixer fixer) - { - fixer.setChoiceSubject(((LSend) child).src.toName()); - } - - @Override - public LMessageTransfer leaveExplicitCorrelationCheck(ScribNode parent, ScribNode child, ExplicitCorrelationChecker checker, ScribNode visited) throws ScribbleException - { - LMessageTransfer lmt = (LMessageTransfer) visited; - checker.pushEnv(checker.popEnv().disableAccept()); - return lmt; - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LSimpleInteractionNodeDel.java b/scribble-core/src/main/java/org/scribble/del/local/LSimpleInteractionNodeDel.java deleted file mode 100644 index 32cf6592b..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LSimpleInteractionNodeDel.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 LSimpleInteractionNodeDel extends LInteractionNodeDel -{ - -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LWrapClientDel.java b/scribble-core/src/main/java/org/scribble/del/local/LWrapClientDel.java deleted file mode 100644 index 7891c4ced..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LWrapClientDel.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ast.ScribNode; -import org.scribble.ast.local.LWrapClient; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ConnectionActionDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.Role; -import org.scribble.visit.context.EGraphBuilder; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; - -public class LWrapClientDel extends ConnectionActionDel implements LSimpleInteractionNodeDel -{ - @Override - public LWrapClient leaveEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder builder, ScribNode visited) throws ScribbleException - { - LWrapClient lc = (LWrapClient) visited; - RoleNode dest = lc.dest; - Role peer = dest.toName(); - builder.util.addEdge(builder.util.getEntry(), builder.job.ef.newEWrapClient(peer), builder.util.getExit()); - return (LWrapClient) super.leaveEGraphBuilding(parent, child, builder, lc); - } - - @Override - public void enterProjectedChoiceSubjectFixing(ScribNode parent, ScribNode child, ProjectedChoiceSubjectFixer fixer) - { - fixer.setChoiceSubject(((LWrapClient) child).src.toName()); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/local/LWrapServerDel.java b/scribble-core/src/main/java/org/scribble/del/local/LWrapServerDel.java deleted file mode 100644 index ccd1163f2..000000000 --- a/scribble-core/src/main/java/org/scribble/del/local/LWrapServerDel.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ast.ScribNode; -import org.scribble.ast.local.LWrapServer; -import org.scribble.del.ConnectionActionDel; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.Role; -import org.scribble.visit.context.EGraphBuilder; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; -import org.scribble.visit.context.UnguardedChoiceDoProjectionChecker; -import org.scribble.visit.context.env.UnguardedChoiceDoEnv; - -public class LWrapServerDel extends ConnectionActionDel implements LSimpleInteractionNodeDel -{ - @Override - public LWrapServer leaveEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder builder, ScribNode visited) throws ScribbleException - { - LWrapServer la = (LWrapServer) visited; - Role peer = la.src.toName(); - builder.util.addEdge(builder.util.getEntry(), builder.job.ef.newEWrapServer(peer), builder.util.getExit()); - return (LWrapServer) super.leaveEGraphBuilding(parent, child, builder, la); - } - - @Override - public void enterProjectedChoiceSubjectFixing(ScribNode parent, ScribNode child, ProjectedChoiceSubjectFixer fixer) - { - fixer.setChoiceSubject(((LWrapServer) child).src.toName()); - } - - @Override - public void enterUnguardedChoiceDoProjectionCheck(ScribNode parent, ScribNode child, UnguardedChoiceDoProjectionChecker checker) throws ScribbleException - { - super.enterUnguardedChoiceDoProjectionCheck(parent, child, checker); - LWrapServer la = (LWrapServer) child; - UnguardedChoiceDoEnv env = checker.popEnv(); - env = env.setChoiceSubject(la.src.toName()); - checker.pushEnv(env); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/name/AmbigNameNodeDel.java b/scribble-core/src/main/java/org/scribble/del/name/AmbigNameNodeDel.java deleted file mode 100644 index 1524b2a1f..000000000 --- a/scribble-core/src/main/java/org/scribble/del/name/AmbigNameNodeDel.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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; - -import org.scribble.ast.MessageTransfer; -import org.scribble.ast.PayloadElem; -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ModuleContext; -import org.scribble.ast.name.simple.AmbigNameNode; -import org.scribble.del.ScribDelBase; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.DataTypeKind; -import org.scribble.type.kind.SigKind; -import org.scribble.type.name.AmbigName; -import org.scribble.visit.wf.NameDisambiguator; - -public class AmbigNameNodeDel extends ScribDelBase -{ - public AmbigNameNodeDel() - { - - } - - // Currently only in "message positions (see Scribble.g ambiguousname) - @Override - public ScribNode leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - ModuleContext mcontext = disamb.getModuleContext(); - AmbigNameNode ann = (AmbigNameNode) visited; - AmbigName name = ann.toName(); - // By well-formedness (checked later), payload type and parameter names are distinct - // FIXME: are conflicts checked elsewhere? - if (mcontext.isDataTypeVisible(name.toDataType())) - { - if (parent instanceof MessageTransfer) // FIXME HACK: MessageTransfer assumes MessageNode (cast in visitChildren), so this needs to be caught here // FIXME: other similar cases? - { - throw new ScribbleException(ann.getSource(), "Invalid occurrence of data type: " + parent); - } - return disamb.job.af.QualifiedNameNode(ann.getSource(), DataTypeKind.KIND, name.getElements()); - } - else if (mcontext.isMessageSigNameVisible(name.toMessageSigName())) - { - if (parent instanceof PayloadElem) // FIXME HACK - { - throw new ScribbleException(ann.getSource(), "Invalid occurrence of message signature name: " + parent); - } - return disamb.job.af.QualifiedNameNode(ann.getSource(), SigKind.KIND, name.getElements()); - } - else if (disamb.isBoundParameter(name)) - { - return disamb.job.af.NonRoleParamNode(ann.getSource(), disamb.getParameterKind(name), name.toString()); - } - throw new ScribbleException(ann.getSource(), "Cannot disambiguate name: " + name); - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/name/DataTypeNodeDel.java b/scribble-core/src/main/java/org/scribble/del/name/DataTypeNodeDel.java deleted file mode 100644 index fdbcfd783..000000000 --- a/scribble-core/src/main/java/org/scribble/del/name/DataTypeNodeDel.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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; - -import org.scribble.ast.DataTypeDecl; -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ModuleContext; -import org.scribble.ast.name.qualified.DataTypeNode; -import org.scribble.del.ScribDelBase; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.DataTypeKind; -import org.scribble.type.name.DataType; -import org.scribble.visit.wf.NameDisambiguator; - -public class DataTypeNodeDel extends ScribDelBase -{ - public DataTypeNodeDel() - { - - } - - // Is this needed? Or DataTypeNodes always created from AmbigNameNode? (in this same pass) - @Override - public ScribNode leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) - throws ScribbleException - { - if (parent instanceof DataTypeDecl) // Hacky? don't want to do for decl simplenames (generally, don't do if parent is namedeclnode) - { - return visited; - } - ModuleContext mc = disamb.getModuleContext(); - DataTypeNode dtn = (DataTypeNode) visited; - DataType dt = dtn.toName(); - if (!mc.isVisibleDataType(dt)) - { - throw new ScribbleException(dtn.getSource(), "Data type not visible: " + dt); - } - DataType fullname = mc.getVisibleDataTypeFullName(dt); - return (DataTypeNode) - disamb.job.af.QualifiedNameNode(dtn.getSource(), DataTypeKind.KIND, fullname.getElements()); // Didn't keep original del - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/name/MessageSigNameNodeDel.java b/scribble-core/src/main/java/org/scribble/del/name/MessageSigNameNodeDel.java deleted file mode 100644 index c6311c825..000000000 --- a/scribble-core/src/main/java/org/scribble/del/name/MessageSigNameNodeDel.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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; - -import org.scribble.ast.MessageSigNameDecl; -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ModuleContext; -import org.scribble.ast.name.qualified.MessageSigNameNode; -import org.scribble.del.ScribDelBase; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.SigKind; -import org.scribble.type.name.MessageSigName; -import org.scribble.visit.wf.NameDisambiguator; - -public class MessageSigNameNodeDel extends ScribDelBase -{ - public MessageSigNameNodeDel() - { - - } - - // Is this needed? Or DataTypeNodes always created from AmbigNameNode? (in this same pass) - @Override - public ScribNode leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - if (parent instanceof MessageSigNameDecl) // Hacky? don't want to do for decl simplenames (generally, don't do if parent is namedeclnode) - { - return visited; - } - ModuleContext mc = disamb.getModuleContext(); - MessageSigNameNode msnn = (MessageSigNameNode) visited; - MessageSigName fullname = mc.getVisibleMessageSigNameFullName(msnn.toName()); - return (MessageSigNameNode) disamb.job.af.QualifiedNameNode(msnn.getSource(), SigKind.KIND, fullname.getElements()); // Didn't keep original del - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/name/ParamNodeDel.java b/scribble-core/src/main/java/org/scribble/del/name/ParamNodeDel.java deleted file mode 100644 index 818993e7b..000000000 --- a/scribble-core/src/main/java/org/scribble/del/name/ParamNodeDel.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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; - -import org.scribble.del.ScribDelBase; - -public class ParamNodeDel extends ScribDelBase -{ - public ParamNodeDel() - { - - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/name/RecVarNodeDel.java b/scribble-core/src/main/java/org/scribble/del/name/RecVarNodeDel.java deleted file mode 100644 index 383eeb27c..000000000 --- a/scribble-core/src/main/java/org/scribble/del/name/RecVarNodeDel.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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; - -import org.scribble.ast.ScribNode; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.del.ScribDelBase; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.RecVarKind; -import org.scribble.type.name.RecVar; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.wf.NameDisambiguator; - -public class RecVarNodeDel extends ScribDelBase -{ - public RecVarNodeDel() - { - - } - - @Override - public RecVarNode leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - // Consistent with bound RoleNode checking - RecVarNode rn = (RecVarNode) visited; - RecVar rv = rn.toName(); - if (!disamb.isBoundRecVar(rv)) - { - throw new ScribbleException(rn.getSource(), "Rec variable not bound: " + rn); - } - return (RecVarNode) super.leaveDisambiguation(parent, child, disamb, rn); - //return super.leaveDisambiguation(parent, child, disamb, rn.reconstruct(disamb.getCanonicalRecVarName(rv))); - } - - @Override - public void enterProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inliner) throws ScribbleException - { - super.enterProtocolInlining(parent, child, inliner); - ScribDelBase.pushVisitorEnv(this, inliner); - } - - @Override - public ScribNode leaveProtocolInlining(ScribNode parent, ScribNode child, ProtocolDefInliner inliner, ScribNode visited) throws ScribbleException - { - RecVarNode rn = (RecVarNode) visited; - RecVar rv = rn.toName(); - //return super.leaveProtocolInlining(parent, child, inliner, rn.reconstruct(inliner.getCanonicalRecVarName(rv))); // No, affects the source AST - //RecVarNode inlined = rn.reconstruct(inliner.getCanonicalRecVarName(rv)); - RecVarNode inlined = (RecVarNode) inliner.job.af.SimpleNameNode(rn.getSource(), RecVarKind.KIND, inliner.getCanonicalRecVarName(rv)); - inliner.pushEnv(inliner.popEnv().setTranslation(inlined)); - return ScribDelBase.popAndSetVisitorEnv(this, inliner, rn); // Not done by any super - } -} diff --git a/scribble-core/src/main/java/org/scribble/del/name/RoleNodeDel.java b/scribble-core/src/main/java/org/scribble/del/name/RoleNodeDel.java deleted file mode 100644 index de064d082..000000000 --- a/scribble-core/src/main/java/org/scribble/del/name/RoleNodeDel.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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; - -import org.scribble.ast.ScribNode; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.del.ScribDelBase; -import org.scribble.main.ScribbleException; -import org.scribble.visit.wf.NameDisambiguator; - -public class RoleNodeDel extends ScribDelBase -{ - public RoleNodeDel() - { - - } - - @Override - public RoleNode leaveDisambiguation(ScribNode parent, ScribNode child, NameDisambiguator disamb, ScribNode visited) throws ScribbleException - { - RoleNode rn = (RoleNode) visited; - if (!disamb.isBoundRole(rn.toName())) - { - throw new ScribbleException(rn.getSource(), "Role not bound: " + rn); - } - return rn; - } -} diff --git a/scribble-core/src/main/java/org/scribble/main/DefaultModuleLoader.java b/scribble-core/src/main/java/org/scribble/main/DefaultModuleLoader.java deleted file mode 100644 index 907dc8652..000000000 --- a/scribble-core/src/main/java/org/scribble/main/DefaultModuleLoader.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 org.scribble.ast.AstFactory; -import org.scribble.ast.Module; -import org.scribble.main.resource.Resource; -import org.scribble.type.name.ModuleName; -import org.scribble.util.Pair; -import org.scribble.util.ScribParserException; - - -/** - * This class provides a default implementation of the module loader interface. - * - */ -public abstract class DefaultModuleLoader implements ModuleLoader -{ - // A caching mechanism? -- not currently used for anything meaningful - // FIXME: redundant? Modules recorded (and updated) in MainContext - // ModuleName is full module name - private java.util.Map> _modules=new java.util.HashMap<>(); - - /** - * This method registers the supplied module. - * - * @param module The module - */ - public void registerModule(Resource res, Module module) - { - _modules.put(module.getFullModuleName(), new Pair<>(res, module)); - } - - /** - * {@inheritDoc} - * @throws ScribParserException - */ - @Override - public Pair loadModule(ModuleName modname, AstFactory af) throws ScribParserException, ScribbleException - { - return (_modules.get(modname)); - } -} diff --git a/scribble-core/src/main/java/org/scribble/main/Job.java b/scribble-core/src/main/java/org/scribble/main/Job.java deleted file mode 100644 index 8eeb02980..000000000 --- a/scribble-core/src/main/java/org/scribble/main/Job.java +++ /dev/null @@ -1,314 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import org.scribble.ast.AstFactory; -import org.scribble.ast.Module; -import org.scribble.del.local.LProtocolDeclDel; -import org.scribble.model.endpoint.EGraph; -import org.scribble.model.endpoint.EGraphBuilderUtil; -import org.scribble.model.endpoint.EModelFactory; -import org.scribble.model.global.SGraph; -import org.scribble.model.global.SGraphBuilderUtil; -import org.scribble.model.global.SModelFactory; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.LProtocolName; -import org.scribble.type.name.ModuleName; -import org.scribble.type.name.Role; -import org.scribble.visit.AstVisitor; -import org.scribble.visit.InlinedProtocolUnfolder; -import org.scribble.visit.ProtocolDefInliner; -import org.scribble.visit.context.ModuleContextBuilder; -import org.scribble.visit.context.ProjectedChoiceDoPruner; -import org.scribble.visit.context.ProjectedChoiceSubjectFixer; -import org.scribble.visit.context.ProjectedRoleDeclFixer; -import org.scribble.visit.context.Projector; -import org.scribble.visit.context.ProtocolDeclContextBuilder; -import org.scribble.visit.util.RoleCollector; -import org.scribble.visit.validation.GProtocolValidator; -import org.scribble.visit.wf.DelegationProtocolRefChecker; -import org.scribble.visit.wf.ExplicitCorrelationChecker; -import org.scribble.visit.wf.NameDisambiguator; -import org.scribble.visit.wf.ReachabilityChecker; -import org.scribble.visit.wf.WFChoiceChecker; - -// A "compiler job" front-end that supports operations comprising visitor passes over the AST and/or local/global models -public class Job -{ - // FIXME: verbose/debug printing parameter: should be in MainContext, but currently cannot access that class directly from here - //public final boolean jUnit; - public final boolean debug; - public final boolean useOldWf; - public final boolean noProgress; // FIXME: 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; - public final boolean noValidation; - - private final JobContext jcontext; // Mutable (Visitor passes replace modules) - - public final AstFactory af; - public final EModelFactory ef; - public final SModelFactory sf; - - private final SGraphBuilderUtil sgbu; - - // Just take MainContext as arg? -- would need to fix Maven dependencies - //public Job(boolean jUnit, boolean debug, Map parsed, ModuleName main, boolean useOldWF, boolean noLiveness) - public Job(boolean debug, Map parsed, ModuleName main, - boolean useOldWF, boolean noLiveness, boolean minEfsm, boolean fair, boolean noLocalChoiceSubjectCheck, - boolean noAcceptCorrelationCheck, boolean noValidation, - AstFactory af, EModelFactory ef, SModelFactory sf) - { - //this.jUnit = jUnit; - 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.af = af; - this.ef = ef; - this.sf = sf; - - this.sgbu = sf.newSGraphBuilderUtil(); - - this.jcontext = new JobContext(this, parsed, main); // Single instance per Job and should never be shared - } - - // Scribble extensions should override these "new" methods - // FIXME: move to MainContext::newJob? - public EGraphBuilderUtil newEGraphBuilderUtil() - { - return new EGraphBuilderUtil(this.ef); - } - - //public SGraphBuilderUtil newSGraphBuilderUtil() // FIXME TODO global builder util - public SGraph buildSGraph(GProtocolName fullname, Map egraphs, boolean explicit) throws ScribbleException - { - for (Role r : egraphs.keySet()) - { - // FIXME: refactor - debugPrintln("(" + fullname + ") Building global model using EFSM for " + r + ":\n" + egraphs.get(r).init.toDot()); - } - //return SGraph.buildSGraph(this, fullname, createInitialSConfig(this, egraphs, explicit)); - return this.sgbu.buildSGraph(this, fullname, egraphs, explicit); // FIXME: factor out util - } - - public void checkWellFormedness() throws ScribbleException - { - runContextBuildingPasses(); - runUnfoldingPass(); - runWellFormednessPasses(); - } - - public void runContextBuildingPasses() throws ScribbleException - { - runVisitorPassOnAllModules(ModuleContextBuilder.class); // Always done first (even if other contexts are built later) so that following passes can use ModuleContextVisitor - runVisitorPassOnAllModules(NameDisambiguator.class); // Includes validating names used in subprotocol calls.. - runVisitorPassOnAllModules(ProtocolDeclContextBuilder.class); //..which this pass depends on. This pass basically builds protocol dependency info - runVisitorPassOnAllModules(DelegationProtocolRefChecker.class); // Must come after ProtocolDeclContextBuilder - runVisitorPassOnAllModules(RoleCollector.class); // Actually, this is the second part of protocoldecl context building - runVisitorPassOnAllModules(ProtocolDefInliner.class); - //runUnfoldingPass(); - } - - // "Second part" of context building (separated for extensions to work on non-unfolded protos -- e.g., Assrt/F17CommandLine) - public void runUnfoldingPass() throws ScribbleException - { - runVisitorPassOnAllModules(InlinedProtocolUnfolder.class); - } - - public void runWellFormednessPasses() throws ScribbleException - { - if (!this.noValidation) - { - runVisitorPassOnAllModules(WFChoiceChecker.class); // For enabled roles and disjoint enabling messages -- includes connectedness checks - runProjectionPasses(); - runVisitorPassOnAllModules(ReachabilityChecker.class); // Moved before GlobalModelChecker.class, OK? - if (!this.useOldWf) - { - runVisitorPassOnAllModules(GProtocolValidator.class); - } - } - } - - // 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() throws ScribbleException - { - runVisitorPassOnAllModules(Projector.class); - runProjectionContextBuildingPasses(); - runProjectionUnfoldingPass(); - if (!noAcceptCorrelationCheck) - { - runVisitorPassOnParsedModules(ExplicitCorrelationChecker.class); - } - } - - // To be done as a barrier pass after projection done on all Modules -- N.B. Module context building, no other validation (so "fixing" can be done in following passes) - // Also does projection "fixing" (choice subjects, subprotocol roledecls) - protected void runProjectionContextBuildingPasses() throws ScribbleException - { - runVisitorPassOnProjectedModules(ModuleContextBuilder.class); - runVisitorPassOnProjectedModules(ProtocolDeclContextBuilder.class); - runVisitorPassOnProjectedModules(RoleCollector.class); // NOTE: doesn't collect from choice subjects (may be invalid until projected choice subjs fixed) - runVisitorPassOnProjectedModules(ProjectedChoiceDoPruner.class); - if (!this.noLocalChoiceSubjectCheck) - { - // Disabling ProjectedChoiceSubjectFixer (local choice subject inference) goes towards a general global WF, but is currently unsound - runVisitorPassOnProjectedModules(ProjectedChoiceSubjectFixer.class); // Must come before other passes that need DUMMY role occurrences to be fixed - } - runVisitorPassOnProjectedModules(ProjectedRoleDeclFixer.class); // Possibly could do after inlining, and do role collection on the inlined version - runVisitorPassOnProjectedModules(ProtocolDefInliner.class); - } - - // Cf. runUnfoldingPass - protected void runProjectionUnfoldingPass() throws ScribbleException - { - runVisitorPassOnProjectedModules(InlinedProtocolUnfolder.class); - } - - // Pre: checkWellFormedness - // Returns: full proto name -> Module - public Map getProjections(GProtocolName fullname, Role role) throws ScribbleException - { - Module root = this.jcontext.getProjection(fullname, role); - Map> dependencies = - ((LProtocolDeclDel) root.getLocalProtocolDecls().get(0).del()) - .getProtocolDeclContext().getDependencyMap().getDependencies().get(role); - // Can ignore Set for projections (is singleton), as each projected proto is a dependency only for self (implicit in the protocoldecl) - return dependencies.keySet().stream().collect( - Collectors.toMap((lpn) -> lpn, (lpn) -> this.jcontext.getModule(lpn.getPrefix()))); - } - - /*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; - }*/ - - public void runVisitorPassOnAllModules(Class c) throws ScribbleException - { - debugPrintPass("Running " + c + " on all modules:"); - runVisitorPass(this.jcontext.getFullModuleNames(), c); - } - - public void runVisitorPassOnParsedModules(Class c) throws ScribbleException - { - debugPrintPass("Running " + c + " on parsed modules:"); - runVisitorPass(this.jcontext.getParsedFullModuleNames(), c); - } - - public void runVisitorPassOnProjectedModules(Class c) throws ScribbleException - { - debugPrintPass("Running " + c + " on projected modules:"); - runVisitorPass(this.jcontext.getProjectedFullModuleNames(), c); - } - - private void runVisitorPass(Set modnames, Class c) throws ScribbleException - { - try - { - Constructor cons = c.getConstructor(Job.class); - for (ModuleName modname : modnames) - { - AstVisitor nv = cons.newInstance(this); - runVisitorOnModule(modname, nv); - } - } - catch (NoSuchMethodException | SecurityException | InstantiationException - | IllegalAccessException | IllegalArgumentException - | InvocationTargetException e) - { - throw new RuntimeException(e); - } - } - - private void runVisitorOnModule(ModuleName modname, AstVisitor nv) throws ScribbleException - { - Module visited = (Module) this.jcontext.getModule(modname).accept(nv); - this.jcontext.replaceModule(visited); - } - - public JobContext getContext() - { - return this.jcontext; - } - - public boolean isDebug() - { - return this.debug; - } - - public void warningPrintln(String s) - { - System.err.println("[Warning] " + s); - } - - public void debugPrintln(String s) - { - if (this.debug) - { - System.out.println(s); - } - } - - private void debugPrintPass(String s) - { - debugPrintln("\n[Job] " + s); - } -} diff --git a/scribble-core/src/main/java/org/scribble/main/JobContext.java b/scribble-core/src/main/java/org/scribble/main/JobContext.java deleted file mode 100644 index c89b1496c..000000000 --- a/scribble-core/src/main/java/org/scribble/main/JobContext.java +++ /dev/null @@ -1,324 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.io.File; -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.GProtocolDecl; -import org.scribble.model.endpoint.AutParser; -import org.scribble.model.endpoint.EGraph; -import org.scribble.model.global.SGraph; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.LProtocolName; -import org.scribble.type.name.ModuleName; -import org.scribble.type.name.Role; -import org.scribble.util.ScribUtil; -import org.scribble.visit.context.EGraphBuilder; -import org.scribble.visit.context.Projector; - -// 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 -{ - private final Job job; - - public final ModuleName main; - - // ModuleName keys are full module names -- currently the modules read from file, distinguished from the generated projection modules - private final Map parsed;// = new HashMap<>(); - - // LProtocolName is the full local protocol name (module name is the prefix) - private final Map projected = new HashMap<>(); - - private final Map fairEGraphs = new HashMap<>(); - private final Map fairSGraphs = new HashMap<>(); - - private final Map unfairEGraphs = new HashMap<>(); - private final Map unfairSGraphs = new HashMap<>(); - - private final Map minimisedEGraphs = 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 - - protected JobContext(Job job, Map parsed, ModuleName main) - { - this.job = job; - - this.parsed = new HashMap(parsed); - this.main = main; - } - - public Module getMainModule() - { - return getModule(this.main); - } - - // Used by Job for pass running, includes projections (e.g. for reachability checking) - // 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() - { - Set modnames = new HashSet<>(); - modnames.addAll(this.parsed.keySet()); - return modnames; - } - - public Set getProjectedFullModuleNames() - { - return this.projected.keySet().stream().map((lpn) -> lpn.getPrefix()).collect(Collectors.toSet()); - } - - /*public boolean hasModule(ModuleName fullname) - { - return isParsedModule(fullname) || isProjectedModule(fullname); - }*/ - - private boolean isParsedModule(ModuleName fullname) - { - return this.parsed.containsKey(fullname); - } - - private boolean isProjectedModule(ModuleName fullname) - { - //return this.projected.keySet().stream().filter((lpn) -> lpn.getPrefix().equals(fullname)).count() > 0; - return getProjectedFullModuleNames().contains(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); - } - } - - // Make context immutable? (will need to assign updated context back to Job) -- will also need to do for Module replacing - public void addProjections(Map> projections) - { - for (GProtocolName gpn : projections.keySet()) - { - Map mods = projections.get(gpn); - for (Role role : mods.keySet()) - { - addProjection(mods.get(role)); - } - } - - /*// Doesn't work for external subprotocols now that Projector doesn't record Module-specific dependencies itself - try - { - ContextBuilder builder = new ContextBuilder(this.job); - for (ProtocolName lpn : this.projections.keySet()) - { - Module mod = this.projections.get(lpn); - mod = (Module) mod.accept(builder); - replaceModule(mod); - } - } - catch (ScribbleException e) - { - throw new RuntimeException("Shouldn't get in here: " + e); - }*/ - } - - private void addProjection(Module mod) - { - LProtocolName lpn = (LProtocolName) mod.getProtocolDecls().get(0).getFullMemberName(mod); - this.projected.put(lpn, mod); - } - - public Module getProjection(GProtocolName fullname, Role role) throws ScribbleException - { - Module proj = this.projected.get(Projector.projectFullProtocolName(fullname, role)); - if (proj == null) - { - throw new ScribbleException("Projection not found: " + fullname + ", " + role); // E.g. disamb/enabling error before projection passes (e.g. CommandLine -fsm arg) - // FIXME: should not occur any more - } - return proj; - } - - protected void addEGraph(LProtocolName fullname, EGraph graph) - { - this.fairEGraphs.put(fullname, graph); - } - - public EGraph getEGraph(GProtocolName fullname, Role role) throws ScribbleException - { - LProtocolName fulllpn = Projector.projectFullProtocolName(fullname, role); - // Moved form LProtocolDecl - EGraph graph = this.fairEGraphs.get(fulllpn); - if (graph == null) - { - Module proj = getProjection(fullname, role); // Projected module contains a single protocol - EGraphBuilder builder = new EGraphBuilder(this.job); // Obtains an EGraphBuilderUtil from Job - proj.accept(builder); - graph = builder.util.finalise(); - addEGraph(fulllpn, graph); - } - return graph; - } - - protected void addUnfairEGraph(LProtocolName fullname, EGraph graph) - { - this.unfairEGraphs.put(fullname, graph); - } - - public EGraph getUnfairEGraph(GProtocolName fullname, Role role) throws ScribbleException - { - LProtocolName fulllpn = Projector.projectFullProtocolName(fullname, role); - - EGraph unfair = this.unfairEGraphs.get(fulllpn); - if (unfair == null) - { - unfair = getEGraph(fullname, role).init.unfairTransform(this.job.ef).toGraph(); - addUnfairEGraph(fulllpn, unfair); - } - return unfair; - } - - protected void addSGraph(GProtocolName fullname, SGraph graph) - { - this.fairSGraphs.put(fullname, graph); - } - - public SGraph getSGraph(GProtocolName fullname) throws ScribbleException - { - SGraph graph = this.fairSGraphs.get(fullname); - if (graph == null) - { - GProtocolDecl gpd = (GProtocolDecl) getModule(fullname.getPrefix()).getProtocolDecl(fullname.getSimpleName()); - Map egraphs = getEGraphsForSGraphBuilding(fullname, gpd, true); - boolean explicit = gpd.modifiers.contains(GProtocolDecl.Modifiers.EXPLICIT); - //graph = SGraph.buildSGraph(egraphs, explicit, this.job, fullname); - graph = this.job.buildSGraph(fullname, egraphs, explicit); - addSGraph(fullname, graph); - } - return graph; - } - - private Map getEGraphsForSGraphBuilding(GProtocolName fullname, GProtocolDecl gpd, boolean fair) throws ScribbleException - { - Map egraphs = new HashMap<>(); - for (Role self : gpd.header.roledecls.getRoles()) - { - egraphs.put(self, fair ? getEGraph(fullname, self) : getUnfairEGraph(fullname, self)); - } - return egraphs; - } - - protected void addUnfairSGraph(GProtocolName fullname, SGraph graph) - { - this.unfairSGraphs.put(fullname, graph); - } - - public SGraph getUnfairSGraph(GProtocolName fullname) throws ScribbleException - { - SGraph graph = this.unfairSGraphs.get(fullname); - if (graph == null) - { - GProtocolDecl gpd = (GProtocolDecl) getModule(fullname.getPrefix()).getProtocolDecl(fullname.getSimpleName()); - Map egraphs = getEGraphsForSGraphBuilding(fullname, gpd, false); - boolean explicit = gpd.modifiers.contains(GProtocolDecl.Modifiers.EXPLICIT); - //graph = SGraph.buildSGraph(this.job, fullname, this.job.createInitialSConfig(job, egraphs, explicit)); - graph = this.job.buildSGraph(fullname, egraphs, explicit); - addUnfairSGraph(fullname, graph); - } - return graph; - } - - protected void addMinimisedEGraph(LProtocolName fullname, EGraph graph) - { - this.minimisedEGraphs.put(fullname, graph); - } - - public EGraph getMinimisedEGraph(GProtocolName fullname, Role role) throws ScribbleException - { - LProtocolName fulllpn = Projector.projectFullProtocolName(fullname, role); - - EGraph minimised = this.minimisedEGraphs.get(fulllpn); - if (minimised == null) - { - String aut = runAut(getEGraph(fullname, role).init.toAut(), fulllpn + ".aut"); - minimised = new AutParser(this.job).parse(aut); - addMinimisedEGraph(fulllpn, minimised); - } - return minimised; - } - - // Duplicated from CommandLine.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 ScribbleException - { - 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/main/RuntimeScribbleException.java b/scribble-core/src/main/java/org/scribble/main/RuntimeScribbleException.java deleted file mode 100644 index 22d09f88a..000000000 --- a/scribble-core/src/main/java/org/scribble/main/RuntimeScribbleException.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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; - -public class RuntimeScribbleException extends RuntimeException -{ - /** - * - */ - private static final long serialVersionUID = 1L; - - public RuntimeScribbleException() - { - // TODO Auto-generated constructor stub - } - - public RuntimeScribbleException(String arg0) - { - super(arg0); - // TODO Auto-generated constructor stub - } - - public RuntimeScribbleException(Throwable arg0) - { - super(arg0); - // TODO Auto-generated constructor stub - } - - public RuntimeScribbleException(String arg0, Throwable arg1) - { - super(arg0, arg1); - // TODO Auto-generated constructor stub - } - - public RuntimeScribbleException(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/main/ScribbleException.java b/scribble-core/src/main/java/org/scribble/main/ScribbleException.java deleted file mode 100644 index b231ba9e0..000000000 --- a/scribble-core/src/main/java/org/scribble/main/ScribbleException.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 org.antlr.runtime.tree.CommonTree; - -public class ScribbleException extends AntlrSourceException -{ - /** - * - */ - private static final long serialVersionUID = 1L; - - public ScribbleException() - { - // TODO Auto-generated constructor stub - } - - public ScribbleException(CommonTree blame, String arg0) - { - super(blame, arg0); - } - - public ScribbleException(String arg0) - { - super(arg0); - // TODO Auto-generated constructor stub - } - - public ScribbleException(Throwable arg0) - { - super(arg0); - // TODO Auto-generated constructor stub - } - - public ScribbleException(String arg0, Throwable arg1) - { - super(arg0, arg1); - // TODO Auto-generated constructor stub - } - - public ScribbleException(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/main/resource/DirectoryResourceLocator.java b/scribble-core/src/main/java/org/scribble/main/resource/DirectoryResourceLocator.java deleted file mode 100644 index b000a233a..000000000 --- a/scribble-core/src/main/java/org/scribble/main/resource/DirectoryResourceLocator.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.LinkedList; -import java.util.List; - -import org.scribble.main.ScribbleException; - -/** - * This class provides a directory based resource locator. - * - */ -// FIXME: 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); - } - - // FIXME: 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 ScribbleException - { - for (Path impath : this.impaths) - { - Path prefixedpath = impath.resolve(path); - if (Files.exists(prefixedpath)) - { - return openFileInputStreamResource(prefixedpath); - } - } - throw new ScribbleException("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 ScribbleException // FIXME: 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 ScribbleException("File couldn't be opened: " + path); - } - return openFileInputStreamResource(path); - } - - private static FileResource openFileInputStreamResource(Path path) throws ScribbleException - { - try - { - return new FileResource(path, Files.newInputStream(path)); - } - catch (IOException e) - { - throw new ScribbleException(e); - } - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/GraphBuilderUtil.java b/scribble-core/src/main/java/org/scribble/model/GraphBuilderUtil.java deleted file mode 100644 index 4915a322f..000000000 --- a/scribble-core/src/main/java/org/scribble/model/GraphBuilderUtil.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model; - -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; - -// Helper class for EndpointGraphBuilder -- can access the protected setters of S -public abstract class GraphBuilderUtil - , // Action type: labels on edges - S extends MState, // State type - K extends ProtocolKind> // Global/local actions/states -- Need to quantify K explicitly -{ - protected S entry; - protected S exit; // Tracking exit is convenient for merges (otherwise have to generate dummy merge nodes) - - protected GraphBuilderUtil() - { - - } - - //public abstract S newState(Set labs); - - // N.B. must be called before every "new visit", including first - // Separated from constructor in order to use newState - public abstract void init(S init); - - protected void reset(S entry, S exit) // Should be used by init - { - this.entry = entry;//newState(Collections.emptySet()); - this.exit = exit;//newState(Collections.emptySet()); - } - - public void addEntryLabel(L lab) - { - this.entry.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 final void removeEdgeAux(S s, A a, S succ) throws ScribbleException // Exception necessary? - { - s.removeEdge(a, succ); - } - - public S getEntry() - { - return this.entry; - } - - public void setEntry(S entry) - { - this.entry = entry; - } - - public S getExit() - { - return this.exit; - } - - public void setExit(S exit) - { - this.exit = exit; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/MAction.java b/scribble-core/src/main/java/org/scribble/model/MAction.java deleted file mode 100644 index d3ca3bb70..000000000 --- a/scribble-core/src/main/java/org/scribble/model/MAction.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model; - -import org.scribble.type.Payload; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; - -public abstract class MAction -{ - /*private static int count = 0; - - public final int id; // Was using for trace enumeration, but breaks isAcceptable -- but need for non-det models*/ - - public final Role obj; - public final MessageId mid; - public final Payload payload; // EMPTY_PAYLOAD for MessageSigNames - - protected MAction(Role obj, MessageId 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; - } - - public String toStringWithMessageIdHack() - { - String m = this.mid.isMessageSigName() ? "^" + 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 final int hashCode() - { - int hash = 79; - hash = 31 * hash + this.id; - return hash; - }*/ - - /*public boolean equiv(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof ModelAction)) - { - return false; - } - ModelAction a = (ModelAction) o; // Refactor as "compatible" - return a.canEqual(this) && - this.obj.equals(a.obj) && this.mid.equals(a.mid) && this.payload.equals(a.payload); - }*/ - - @Override - public boolean equals(Object o) // FIXME: kind - { - if (this == o) - { - return true; - } - if (!(o instanceof MAction)) - { - return false; - } - MAction a = (MAction) o; // Refactor as "compatible" - return a.canEqual(this) && - this.obj.equals(a.obj) && this.mid.equals(a.mid) && this.payload.equals(a.payload); - //return this.id == ((ModelAction) o).id; - } - - public abstract boolean canEqual(Object o); -} diff --git a/scribble-core/src/main/java/org/scribble/model/MPrettyState.java b/scribble-core/src/main/java/org/scribble/model/MPrettyState.java deleted file mode 100644 index 30f65b294..000000000 --- a/scribble-core/src/main/java/org/scribble/model/MPrettyState.java +++ /dev/null @@ -1,164 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; -import java.util.stream.Collectors; - -import org.scribble.type.kind.ProtocolKind; - -public abstract class MPrettyState - , S extends MPrettyState, K extends ProtocolKind> - extends MState - implements MPrettyPrint -{ - public MPrettyState(Set labs) // Immutable singleton node - { - super(labs); - } - - public String toLongString() - { - String s = "\"" + this.id + "\":["; - Iterator ss = this.succs.iterator(); - s += this.actions.stream().map((a) -> a + "=\"" + ss.next().id + "\"").collect(Collectors.joining(", ")); - return s + "]"; - } - - @Override - public final String toDot() - { - String s = "digraph G {\n" // rankdir=LR;\n - + "compound = true;\n"; - s += toDot(new HashSet<>()); - return s + "\n}"; - } - - //protected final String toDot(Set seen) - protected final String toDot(Set> seen) - { - seen.add(this); - String dot = toNodeDot(); - //for (Entry e : this.edges.entrySet()) - for (int i = 0; i < this.actions.size(); i ++) - { - /*A msg = e.getKey(); - S p = e.getValue();*/ - A a = this.actions.get(i); - S s = this.succs.get(i); - dot += "\n" + toEdgeDot(a, s); - if (!seen.contains(s)) - { - dot += "\n" + s.toDot(seen); - } - } - return dot; - } - - protected final String toEdgeDot(String src, String dest, String lab) - { - return src + " -> " + dest + " [ " + lab + " ];"; - } - - // dot node declaration - // Override to change drawing declaration of "this" node - protected String toNodeDot() - { - return getDotNodeId() + " [ " + getNodeLabel() + " ];"; - } - - protected String getNodeLabel() - { - String labs = this.labs.toString(); - //return "label=\"" + labs.substring(1, labs.length() - 1) + "\""; - return "label=\"" + this.id + ": " + labs.substring(1, labs.length() - 1) + "\""; // FIXME - } - - protected String getDotNodeId() - { - return "\"" + this.id + "\""; - } - - // 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 + "\""; - } - - @Override - public final String toAut() - { - Set> all = new HashSet<>(); - all.add(this); - all.addAll(getReachableStates(this)); - String aut = ""; - int edges = 0; - Set seen = new HashSet<>(); - for (MPrettyState s : all) - { - if (seen.contains(s.id)) - { - continue; - } - seen.add(s.id); - Iterator as = s.getAllActions().iterator(); - Iterator ss = s.getAllSuccessors().iterator(); - for (; as.hasNext(); edges++) - { - A a = as.next(); - S succ = ss.next(); - String msg = a.toStringWithMessageIdHack(); // 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 - } - - @Override - public String toString() - { - return Integer.toString(this.id); // FIXME -- ? - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/MState.java b/scribble-core/src/main/java/org/scribble/model/MState.java deleted file mode 100644 index 0dae3bb73..000000000 --- a/scribble-core/src/main/java/org/scribble/model/MState.java +++ /dev/null @@ -1,273 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.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.Set; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; - -public abstract class MState< - L, // Node label type (cosmetic) - A extends MAction, // Edge type - S extends MState, // State type - K extends ProtocolKind // Global/Local -> -{ - private static int count = 0; // FIXME: factor out with ModelAction - - public final int id; - - protected final Set labs; // Was RecVar and SubprotocolSigs, now using inlined protocol for FSM building so just RecVar - - // **: clients should use the pair of getAllAcceptable/getSuccessors for correctness -- getAcceptable/accept don't support non-det - //protected final LinkedHashMap edges; // Want predictable ordering of entries for e.g. API generation (state enumeration)*/ - protected final List actions; - protected final List succs; - - public MState(Set labs) // Immutable singleton node - { - this.id = MState.count++; - this.labs = new HashSet<>(labs); - this.actions = new LinkedList<>(); - this.succs = new LinkedList<>(); - } - - protected final void addLabel(L lab) - { - this.labs.add(lab); - } - - public final Set getLabels() - { - return Collections.unmodifiableSet(this.labs); - } - - // Mutable (can also overwrite edges) - protected void addEdge(A a, S s) - //public final void addEdge(A a, S s) // FIXME: currently public for SGraph building -- make a global version of EGraphBuilderUtil - { - //this.edges.put(a, s); - Iterator as = this.actions.iterator(); // Needed?.. - Iterator ss = this.succs.iterator(); - while (as.hasNext()) // Duplicate edges preemptively pruned here, but could leave to later minimisation - { - A tmpa = as.next(); - S tmps = ss.next(); - if (tmpa.equals(a) && tmps.equals(s)) - { - return; - } - } // ..needed? - this.actions.add(a); - this.succs.add(s); - } - - protected final void removeEdge(A a, S s) throws ScribbleException - { - Iterator ia = this.actions.iterator(); - Iterator is = this.succs.iterator(); - while (ia.hasNext()) - { - A tmpa = ia.next(); - S tmps = is.next(); - if (tmpa.equals(a) && tmps.equals(s)) - { - ia.remove(); - is.remove(); - return; - } - } - //throw new RuntimeException("No such transition to remove: " + a + "->" + s); - throw new ScribbleException("No such transition to remove: " + a + "->" + s); // Hack? EFSM building on bad-reachability protocols now done before actual reachability check - } - - // The "deterministic" variant, cf., getAllActions - public final List getActions() - { - Set as = new HashSet<>(this.actions); - if (as.size() != this.actions.size()) - { - throw new RuntimeScribbleException("[TODO] Non-deterministic state: " + this.actions + " (Try -minlts if available)"); // This getter checks for determinism -- affects e.g. API generation - } - //return as; - return getAllActions(); - } - - public final List getAllActions() - { - return Collections.unmodifiableList(this.actions); - } - - public final boolean hasAction(A a) - { - return this.actions.contains(a); - } - - public S getSuccessor(A a) - { - Set as = new HashSet<>(this.actions); - if (as.size() != this.actions.size()) - { - throw new RuntimeException("FIXME: " + this.actions); - } - return getSuccessors(a).get(0); - } - - public final List getSuccessors() - { - Set as = new HashSet<>(this.actions); - if (as.size() != this.actions.size()) - { - throw new RuntimeScribbleException("[TODO] Non-deterministic state: " + this.actions + " (Try -minlts if available)"); // This getter checks for determinism -- affects e.g. API generation - } - return getAllSuccessors(); - } - - // For non-deterministic actions - public final List getSuccessors(A a) - { - return IntStream.range(0, this.actions.size()) - .filter((i) -> this.actions.get(i).equals(a)) - .mapToObj((i) -> this.succs.get(i)) - .collect(Collectors.toList()); - } - - public final List getAllSuccessors() - { - return Collections.unmodifiableList(this.succs); - } - - public final boolean isTerminal() - { - return this.actions.isEmpty(); - } - - public static , S extends MState, K extends ProtocolKind> - S getTerminal(S start) - { - if (start.isTerminal()) - { - return start; - } - Set terms = MState.getReachableStates(start).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? - } - - public boolean canReach(MState s) - { - return MState.getReachableStates(this).contains(s); - } - - // 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)*/ - @SuppressWarnings("unchecked") - public static , S extends MState, K extends ProtocolKind> - 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") - public static , S extends MState, K extends ProtocolKind> - //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; - } - - @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; - } - return ((MState) o).canEquals(this) && this.id == ((MState) o).id; // Good to use id, due to edge mutability - } - - protected abstract boolean canEquals(MState s); - - @Override - public String toString() - { - return Integer.toString(this.id); // FIXME -- ? - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/endpoint/AutParser.java b/scribble-core/src/main/java/org/scribble/model/endpoint/AutParser.java deleted file mode 100644 index b4391dc4b..000000000 --- a/scribble-core/src/main/java/org/scribble/model/endpoint/AutParser.java +++ /dev/null @@ -1,289 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.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.main.Job; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.Payload; -import org.scribble.type.name.DataType; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.MessageSigName; -import org.scribble.type.name.Op; -import org.scribble.type.name.Role; - -public class AutParser -{ - private final Job job; - - public AutParser(Job job) - { - this.job = job; - } - - public EGraph parse(String aut) - { - EModelFactory ef = job.ef; - - //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 = job.newEGraphBuilderUtil(); - 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.ef.newEState(Collections.emptySet())); - } - } - //for (int i : succs) - for (int i : succs.keySet()) - { - if (!map.containsKey(i) && i != init && i != term) - { - map.put(i, util.ef.newEState(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 builder.finalise(); - return new EGraph(util.getEntry(), util.getExit()); - } - - // Cf. getCommSymbol of IOActions - // FIXME: simply do a match for getCommSymbol? - private static EAction parseIOAction(EModelFactory ef, String a) - { - String peer; - String action; - String msg; // Could be an Op or a MessageSigName (affects API generation) - String[] pay = 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()) - { - pay = p.split(","); - } - switch (action) - { - case "!": - { - Payload payload = (pay != null) ? new Payload(Arrays.asList(pay).stream().map((pe) -> new DataType(pe)).collect(Collectors.toList())) : Payload.EMPTY_PAYLOAD; - return ef.newESend(new Role(peer), getMessageIdHack(msg), payload); // FIXME: how about MessageSigNames? -- currently OK, treated as empty payload (cf. ModelAction) - } - case "?": - { - Payload payload = (pay != null) ? new Payload(Arrays.asList(pay).stream().map((pe) -> new DataType(pe)).collect(Collectors.toList())) : Payload.EMPTY_PAYLOAD; - return ef.newEReceive(new Role(peer), getMessageIdHack(msg), payload); // FIXME: how about MessageSigNames?) - } - case "!!": - { - //return new Connect(new Role(peer)); - Payload payload = (pay != null) ? new Payload(Arrays.asList(pay).stream().map((pe) -> new DataType(pe)).collect(Collectors.toList())) : Payload.EMPTY_PAYLOAD; - return ef.newERequest(new Role(peer), getMessageIdHack(msg), payload); - } - case "??": - { - //return new Accept(new Role(peer)); - Payload payload = (pay != null) ? new Payload(Arrays.asList(pay).stream().map((pe) -> new DataType(pe)).collect(Collectors.toList())) : Payload.EMPTY_PAYLOAD; - return ef.newEAccept(new Role(peer), getMessageIdHack(msg), payload); - } - case "(!!)": - { - return ef.newEWrapClient(new Role(peer)); - } - case "(??)": - { - return ef.newEWrapServer(new Role(peer)); - } - case "-/-": - { - return ef.newEDisconnect(new Role(peer)); - } - default: - { - throw new RuntimeException("[TODO] aut parsing not supported for: " + msg); - } - } - } - - // Cf. ModelState.toAut, ModelAction.toStringWithMessageIdHack - private static MessageId getMessageIdHack(String msg) - { - return (msg.startsWith("^")) ? new MessageSigName(msg.substring(1)) : new Op(msg); - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/endpoint/EFSM.java b/scribble-core/src/main/java/org/scribble/model/endpoint/EFSM.java deleted file mode 100644 index 815bd20e6..000000000 --- a/scribble-core/src/main/java/org/scribble/model/endpoint/EFSM.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.endpoint; - -import java.util.List; -import java.util.stream.Collectors; - -import org.scribble.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;//new EGraph(init, term); - this.curr = curr; - } - - /*public EndpointState getCurrent() - { - return this.curr; - }*/ - - // CHECKME: check if unfolded initial accept is possible, and if it breaks anything - public boolean isInitial() - { - return this.curr.equals(this.graph.init); - } - - public boolean isTerminated() - { - return this.curr.isTerminal(); - } - - public EStateKind getStateKind() - { - return this.curr.getStateKind(); - } - - public List fireAll(EAction a) - { - return this.curr.getSuccessors(a).stream().map((s) -> new EFSM(this.graph, s)).collect(Collectors.toList()); - } - - public List getAllFireable() - { - return this.curr.getAllActions(); - } - - public boolean hasFireable(EAction a) - { - return this.curr.hasAction(a); - } - - public boolean isConnectOrWrapClientOnly() - { - return this.curr.isConnectOrWrapClientOnly(); - } - - @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); - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/endpoint/EGraph.java b/scribble-core/src/main/java/org/scribble/model/endpoint/EGraph.java deleted file mode 100644 index 19e2180e0..000000000 --- a/scribble-core/src/main/java/org/scribble/model/endpoint/EGraph.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.endpoint; - -import org.scribble.model.MPrettyPrint; - -public class EGraph implements MPrettyPrint -{ - public final EState init; - public final EState term; - - //protected EGraph(EState init, EState term) - public EGraph(EState init, EState term) - { - this.init = init; - this.term = term; - } - - public EFSM toFsm() - { - return new EFSM(this); - } - - @Override - public String toAut() - { - return this.init.toAut(); - } - - @Override - public String toDot() - { - return this.init.toDot(); - } - - @Override - public final int hashCode() - { - int hash = 1051; - hash = 31 * hash + this.init.hashCode(); // FIXME: uses (init) state ID only -- although OK since state IDs globall 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? - } - - @Override - public String toString() - { - return this.init.toString(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/endpoint/EGraphBuilderUtil.java b/scribble-core/src/main/java/org/scribble/model/endpoint/EGraphBuilderUtil.java deleted file mode 100644 index d771f8b57..000000000 --- a/scribble-core/src/main/java/org/scribble/model/endpoint/EGraphBuilderUtil.java +++ /dev/null @@ -1,503 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.endpoint; - -import java.util.Arrays; -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.main.ScribbleException; -import org.scribble.model.GraphBuilderUtil; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.model.global.SModelFactory; -import org.scribble.model.global.actions.SAction; -import org.scribble.type.Payload; -import org.scribble.type.kind.Local; -import org.scribble.type.name.Op; -import org.scribble.type.name.RecVar; -import org.scribble.type.name.Role; - -// Helper class for EGraphBuilder -- can access the protected setters of EState (via superclass helper methods) -// Tailored to support graph building from syntactic local protocol choice and recursion -public class EGraphBuilderUtil extends GraphBuilderUtil -{ - public final EModelFactory ef; - - private final Map> recvars = new HashMap<>(); - //private final Map>> enacting = new HashMap<>(); // First action(s) inside a rec scope ("enacting" means how to enact an unguarded choice-continue) - private final Map>> enacting = new HashMap<>(); - // CHECKME: Set sufficient? or List? (consider non-determinism -- does it matter?) - - //private final Map>> enactingMap = new HashMap<>(); // Record enacting per-recvar, since a state could have multi-recvars - private final Map>> enactingMap = new HashMap<>(); - - private final Deque> pred = new LinkedList<>(); - private final Deque> prev = new LinkedList<>(); - - public EGraphBuilderUtil(EModelFactory ef) - { - this.ef = ef; - ////clear(); - //reset(); - } - - // N.B. must be called before every "new visit", including first - @Override - public void init(EState init) - { - clear(); - reset(this.ef.newEState(Collections.emptySet()), this.ef.newEState(Collections.emptySet())); - } - - protected void clear() - { - this.recvars.clear(); - this.enacting.clear(); - - this.pred.clear(); - this.pred.push(new LinkedList<>()); - - this.prev.clear(); - this.prev.push(new LinkedList<>()); - - this.enactingMap.clear(); - } - - /*@Override - public EState newState(Set labs) - { - return new EState(labs); - }*/ - - // 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) - { - addEdgeAux(s, a, succ); - - //if (!this.pred.isEmpty()) - { - this.pred.pop(); - this.prev.pop(); - } - this.pred.push(new LinkedList<>(Arrays.asList(s))); - this.prev.push(new LinkedList<>(Arrays.asList(a))); - - //for (Deque> ens : this.enacting.values()) - for (Deque> ens : this.enacting.values()) - { - if (!ens.isEmpty()) // Unnecessary? - { - //Set tmp = ens.peek(); - List tmp = ens.peek(); - if (tmp.isEmpty()) - { - tmp.add(a); - } - } - } - } - - - /* - * Dealing with Choice contexts - */ - public void enterChoice() - { - this.pred.push(new LinkedList<>()); - this.prev.push(new LinkedList<>()); - - for (RecVar rv : this.enacting.keySet()) - { - ////Deque> tmp = this.enacting.get(rv); - Deque> tmp = this.enacting.get(rv); - ////tmp.push(new HashSet<>(tmp.peek())); - //tmp.push(new HashSet<>()); // Initially empty to record nested enablings in choice blocks - tmp.push(new LinkedList<>()); // Initially empty to record nested enablings in choice blocks - } - } - - public void leaveChoice() - { - List pred = this.pred.pop(); - List prev = this.prev.pop(); - if (!pred.isEmpty()) - { - this.pred.pop(); - this.prev.pop(); - this.pred.push(pred); - this.prev.push(prev); - } - - for (RecVar rv : this.enacting.keySet()) - { - /*Set pop = this.enacting.get(rv).pop(); - Set peek = this.enacting.get(rv).peek();*/ - List pop = this.enacting.get(rv).pop(); - List peek = this.enacting.get(rv).peek(); - if (peek.isEmpty()) // Cf. addEdge - { - peek.addAll(pop); - } - } - } - - public void pushChoiceBlock() - { - this.pred.push(null); // Signifies following statement is "unguarded" in this choice block - this.prev.push(null); - - for (RecVar rv : this.enacting.keySet()) - { - //Deque> tmp = this.enacting.get(rv); - Deque> tmp = this.enacting.get(rv); - //tmp.push(new HashSet<>()); // Must be empty for addEdge to record (nested) enabling - tmp.push(new LinkedList<>()); - } - } - - public void popChoiceBlock() - { - List pred = this.pred.pop(); - List prev = this.prev.pop(); - - if (pred != null) // Unguarded choice-continue? - { - List peek1 = this.pred.peek(); - if (peek1 == null) - { - this.pred.pop(); - peek1 = new LinkedList<>(); - this.pred.push(peek1); - } - peek1.addAll(pred); - } - - if (prev != null) - { - List peek2 = this.prev.peek(); - if (peek2 == null) - { - this.prev.pop(); - peek2 = new LinkedList<>(); - this.prev.push(peek2); - } - peek2.addAll(prev); - } - - for (RecVar rv : this.enacting.keySet()) - { - /*Set pop = this.enacting.get(rv).pop(); - Set peek = this.enacting.get(rv).peek();*/ - List pop = this.enacting.get(rv).pop(); - List peek = this.enacting.get(rv).peek(); - //if (peek.isEmpty()) - { - peek.addAll(pop); - } - } - } - - - /* - * Dealing with Recursion contexts - */ - public void pushRecursionEntry(RecVar recvar, EState entry) - { - /*if (!isUnguardedInChoice()) // Don't record rec entry if it is an unguarded choice-rec - { - this.entry.addLabel(recvar); - }*/ - //this.recvars.put(recvar, this.entry); - Deque tmp = this.recvars.get(recvar); - if (tmp == null) - { - tmp = new LinkedList<>(); - this.recvars.put(recvar, tmp); - } - /*if (isUnguardedInChoice()) - { - tmp.push(tmp.peek()); // Works because unguarded recs unfolded (including nested recvar shadowing -- if unguarded choice-rec, it will be unfolded and rec entry recorded for guarded unfolding) - } - else - { - tmp.push(this.entry); - }*/ - tmp.push(entry); - - //Deque> tmp2 = this.enacting.get(recvar); - Deque> tmp2 = this.enacting.get(recvar); - if (tmp2 == null) - { - tmp2 = new LinkedList<>(); // New Stack for this recvar - this.enacting.put(recvar, tmp2); - } - //tmp2.push(new HashSet<>()); // Push new Set element onto stack - tmp2.push(new LinkedList<>()); // Push new Set element onto stack - } - - public void popRecursionEntry(RecVar recvar) - { - this.recvars.get(recvar).pop(); // Pop the entry of this rec - - //Set pop = this.enacting.get(recvar).pop(); - List pop = this.enacting.get(recvar).pop(); - if (this.enacting.get(recvar).isEmpty()) // All Sets popped from the stack of this recvar - { - this.enacting.remove(recvar); - } - - EState curr = getEntry(); - //Map> tmp = this.enactingMap.get(curr); - Map> tmp = this.enactingMap.get(curr); - if (tmp == null) - { - tmp = new HashMap<>(); - this.enactingMap.put(curr, tmp); - } - tmp.put(recvar, pop); - } - - - /* - * Edge construction for Continues - */ - public boolean isUnguardedInChoice() - //public boolean isUnguardedInChoice(RecVar rv) - { - return - ////!this.entry.equals(this.root) && // Hacky? for protocols that start with unguarded choice-rec, e.g. choice at A { rec X { ... at root - //!this.pred.isEmpty() && // This and above fixed by initialising non-null pred/prev? - this.pred.peek() == null; - } - - // Choice-unguarded continues -- fixed in finalise pass - public void addContinueEdge(EState s, RecVar rv) - { - /*this.contStates.add(s); - this.contRecVars.add(rv);*/ - EState entry = getRecursionEntry(rv); - addEdgeAux(s, new IntermediateContinueEdge(this.ef, rv), entry); - //addEdge(s, new IntermediateContinueEdge(rv), entry); // **FIXME: broken on purpose for testing - } - - // Doesn't set predecessor, cf. addEdge (and cf. addEdgeAux) - // Choice-guarded continues (can be done in one pass) - public void addRecursionEdge(EState s, EAction a, EState succ) // Cf. LGraphBuilder.addContinueEdge, for choice-unguarded cases -- addRecursionEdge, for guarded cases, should also be in LGraphBuilder, but here for convenience (private state) - { - addEdgeAux(s, a, succ); - - // Still needed here? - //for (Deque> ens : this.enacting.values()) - for (Deque> ens : this.enacting.values()) - { - if (!ens.isEmpty()) - { - //Set tmp = ens.peek(); - List tmp = ens.peek(); - if (tmp.isEmpty()) - { - tmp.add(a); - } - } - } - } - - // succ assumed to be this.getEntry() - public void removeEdgeFromPredecessor(EState s, EAction a) throws ScribbleException // Removing prev edge, to be replaced by addRecursionEdge - { - //s.removeEdge(a, this.getEntry()); - removeEdgeAux(s, a, this.getEntry()); - //this.pred.peek().remove(s); // Need to update both preds and prevs accordingly (consider non-det) - Iterator preds = this.pred.peek().iterator(); - Iterator prevs = this.prev.peek().iterator(); - while (preds.hasNext()) - { - EState nexts = preds.next(); - EAction nexta = prevs.next(); - if (nexts.equals(s) && nexta.equals(a)) - { - preds.remove(); - prevs.remove(); - return; - } - } - throw new RuntimeException("Shouldn't get in here: " + s + ", " + a); - } - - public List getPredecessors() - { - //return this.pred.peek(); - return new LinkedList<>(this.pred.peek()); // Cf. removeEdgeFromPredecessor - } - - public List getPreviousActions() - { - //return this.prev.peek(); - return new LinkedList<>(this.prev.peek()); - } - - public EState getRecursionEntry(RecVar recvar) - { - return this.recvars.get(recvar).peek(); - } - - - /* - * Finalise graph by treating IntermediateContinueEdges - */ - public EGraph finalise() - { - /*EState res = new EState(this.entry.getLabels()); - EState resTerm = new EState(this.exit.getLabels());*/ - EState res = this.entry.cloneNode(this.ef, this.entry.getLabels()); //this.ef.newEState(this.entry.getLabels()); - EState resTerm = this.exit.cloneNode(this.ef, this.exit.getLabels()); //this.ef.newEState(this.exit.getLabels()); - - Map map = new HashMap<>(); - map.put(this.entry, res); - map.put(this.exit, resTerm); - Set seen = new HashSet<>(); - fixContinueEdges(seen, map, this.entry, res); - if (!seen.contains(this.exit)) - { - resTerm = null; - } - - /*Map all = getAllStates(res); - EndpointState dfa = determinise(all, res, resTerm); - System.out.println("111: " + dfa.toDot());*/ - - return new EGraph(res, resTerm); - } - - // FIXME: incomplete -- won't fully correctly handle situations involving, e.g., transitive continue-edge fixing? - protected void fixContinueEdges(Set seen, Map map, EState curr, EState res) - { - if (seen.contains(curr)) - { - return; - } - seen.add(curr); - Iterator as = curr.getAllActions().iterator(); - Iterator ss = curr.getAllSuccessors().iterator(); - while (as.hasNext()) - { - EAction a = as.next(); - EState succ = ss.next(); - EState next; - next = getNext(map, succ); - - if (!(a instanceof IntermediateContinueEdge)) - { - addEdgeAux(res, a, next); - - fixContinueEdges(seen, map, succ, next); - } - else - { - IntermediateContinueEdge ice = (IntermediateContinueEdge) a; - //for (IOAction e : this.enactingMap.get(succ)) - RecVar rv = new RecVar(ice.mid.toString()); - for (EAction e : this.enactingMap.get(succ).get(rv)) - { - for (EState n : succ.getSuccessors(e)) - { - next = getNext(map, n); - addEdgeAux(res, e, next); - - fixContinueEdges(seen, map, succ, next); - } - } - } - } - } - - private EState getNext(Map map, EState succ) - { - EState next; - if (map.containsKey(succ)) - { - next = map.get(succ); - } - else - { - //next = this.ef.newEState(succ.getLabels()); - next = succ.cloneNode(this.ef, succ.getLabels()); - map.put(succ, next); - } - return next; - } -} - - -class IntermediateContinueEdge extends EAction -{ - public IntermediateContinueEdge(EModelFactory ef, RecVar rv) - { - super(ef, 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(SModelFactory sf, 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 IntermediateContinueEdge)) - { - return false; - } - return ((IntermediateContinueEdge) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof IntermediateContinueEdge; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/endpoint/EModelFactory.java b/scribble-core/src/main/java/org/scribble/model/endpoint/EModelFactory.java deleted file mode 100644 index 43e981467..000000000 --- a/scribble-core/src/main/java/org/scribble/model/endpoint/EModelFactory.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.endpoint; - -import java.util.Set; - -import org.scribble.model.endpoint.actions.EAccept; -import org.scribble.model.endpoint.actions.ERequest; -import org.scribble.model.endpoint.actions.EDisconnect; -import org.scribble.model.endpoint.actions.EReceive; -import org.scribble.model.endpoint.actions.ESend; -import org.scribble.model.endpoint.actions.EWrapClient; -import org.scribble.model.endpoint.actions.EWrapServer; -import org.scribble.type.Payload; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.RecVar; -import org.scribble.type.name.Role; - -public interface EModelFactory -{ - ESend newESend(Role peer, MessageId mid, Payload payload); - EReceive newEReceive(Role peer, MessageId mid, Payload payload); - ERequest newERequest(Role peer, MessageId mid, Payload payload); - EAccept newEAccept(Role peer, MessageId mid, Payload payload); - EDisconnect newEDisconnect(Role peer); - EWrapClient newEWrapClient(Role peer); - EWrapServer newEWrapServer(Role peer); - - EState newEState(Set labs); -} diff --git a/scribble-core/src/main/java/org/scribble/model/endpoint/EModelFactoryImpl.java b/scribble-core/src/main/java/org/scribble/model/endpoint/EModelFactoryImpl.java deleted file mode 100644 index 3505dc96c..000000000 --- a/scribble-core/src/main/java/org/scribble/model/endpoint/EModelFactoryImpl.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.endpoint; - -import java.util.Set; - -import org.scribble.model.endpoint.actions.EAccept; -import org.scribble.model.endpoint.actions.ERequest; -import org.scribble.model.endpoint.actions.EDisconnect; -import org.scribble.model.endpoint.actions.EReceive; -import org.scribble.model.endpoint.actions.ESend; -import org.scribble.model.endpoint.actions.EWrapClient; -import org.scribble.model.endpoint.actions.EWrapServer; -import org.scribble.type.Payload; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.RecVar; -import org.scribble.type.name.Role; - -// Separate E/SModelFactories fits protected E/SState constructor pattern -public class EModelFactoryImpl implements EModelFactory -{ - - @Override - public ESend newESend(Role peer, MessageId mid, Payload payload) - { - return new ESend(this, peer, mid, payload); - } - - @Override - public EReceive newEReceive(Role peer, MessageId mid, Payload payload) - { - return new EReceive(this, peer, mid, payload); - } - - @Override - public ERequest newERequest(Role peer, MessageId mid, Payload payload) - { - return new ERequest(this, peer, mid, payload); - } - - @Override - public EAccept newEAccept(Role peer, MessageId mid, Payload payload) - { - return new EAccept(this, peer, mid, payload); - } - - @Override - public EDisconnect newEDisconnect(Role peer) - { - return new EDisconnect(this, peer); - } - - @Override - public EWrapClient newEWrapClient(Role peer) - { - return new EWrapClient(this, peer); - } - - @Override - public EWrapServer newEWrapServer(Role peer) - { - return new EWrapServer(this, peer); - } - - @Override - public EState newEState(Set labs) - { - return new EState(labs); - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/endpoint/EState.java b/scribble-core/src/main/java/org/scribble/model/endpoint/EState.java deleted file mode 100644 index 0c22bf16b..000000000 --- a/scribble-core/src/main/java/org/scribble/model/endpoint/EState.java +++ /dev/null @@ -1,325 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.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 org.scribble.main.ScribbleException; -import org.scribble.model.MPrettyState; -import org.scribble.model.MState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.type.kind.Local; -import org.scribble.type.name.RecVar; - -// 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 - // FIXME: remove labs arg, and modify the underlying Set if needed? - protected EState cloneNode(EModelFactory ef, Set labs) - { - //return ef.newEState(this.labs); - return ef.newEState(labs); - } - - // 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(this)); // Throws exception if >1 terminal; null if no terminal - } - - /*.. move back to endpointstate - .. 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 EState unfairTransform(EModelFactory ef) - { - EState init = clone(ef); - - EState term = MPrettyState.getTerminal(init); - Set seen = new HashSet<>(); - Set todo = new LinkedHashSet<>(); - todo.add(init); - while (!todo.isEmpty()) - { - Iterator i = todo.iterator(); - EState curr = i.next(); - i.remove(); - - if (seen.contains(curr)) - { - continue; - } - seen.add(curr); - - if (curr.getStateKind() == EStateKind.OUTPUT && curr.getAllActions().size() > 1) // >1 is what makes this algorithm terminating - { - //if (curr.getAllTakeable().size() > 1) - { - Iterator as = curr.getAllActions().iterator(); - Iterator ss = curr.getAllSuccessors().iterator(); - //Map clones = new HashMap<>(); - List cloneas = new LinkedList<>(); - List cloness = new LinkedList<>(); - //LinkedHashMap cloness = new LinkedHashMap<>(); // clone -> original - Map> toRemove = new HashMap<>(); // List needed for multiple edges to remove to the same state: e.g. mu X . (A->B:1 + A->B:2).X - while (as.hasNext()) - { - EAction a = as.next(); - EState s = ss.next(); - if (!s.canReach(curr)) - { - todo.add(s); - } - else - { - EState clone = curr.unfairClone(ef, term, a, s); // s is a succ of curr - //try { s.removeEdge(a, tmps); } catch (ScribbleException e) { throw new RuntimeException(e); } - //clones.put(a, clone); - cloneas.add(a); - cloness.add(clone); - //cloness.put(clone, s); - - //toRemove.put(s, a); - List tmp = toRemove.get(s); - if (tmp == null) - { - tmp = new LinkedList<>(); - toRemove.put(s, tmp); - } - tmp.add(a); - } - } - //if (!clones.isEmpty()) // Redundant, but more clear - if (!cloneas.isEmpty()) // Redundant, but more clear - { - /*as = new LinkedList<>(curr.getAllTakeable()).iterator(); - //Iterator - ss = new LinkedList<>(curr.getSuccessors()).iterator(); - while (as.hasNext()) - { - IOAction a = as.next(); - EndpointState s = ss.next(); - //if (clones.containsKey(a)) // Still OK for non-det edges? - //if (cloneas.contains(a)) // Still OK for non-det edges? -- no: removing *all* non-det a's for this a, so non-recursive cases are lost - if (cloneas.contains(a) && ...succ == orig...) - { - try { curr.removeEdge(a, s); } catch (ScribbleException e) { throw new RuntimeException(e); } - } - }*/ - for (EState s : toRemove.keySet()) - { - try - { - //curr.removeEdge(toRemove.get(s), s); - for (EAction tmp : toRemove.get(s)) - { - curr.removeEdge(tmp, s); - } - } - catch (ScribbleException e) { throw new RuntimeException(e); } - } - //for (Entry e : clones.entrySet()) - Iterator icloneas = cloneas.iterator(); - Iterator icloness = cloness.iterator(); - //Iterator icloness = cloness.keySet().iterator(); - while (icloneas.hasNext()) - { - EAction a = icloneas.next(); - EState s = icloness.next(); - /*curr.addEdge(e.getKey(), e.getValue()); - todo.add(e.getValue()); - seen.add(e.getValue());*/ - curr.addEdge(a, s); - todo.add(s); // Doesn't work if non-det preserved by unfairClone aux (recursively edges>1) - /*seen.add(s); // 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 - todo.addAll(s.getSuccessors());*/ - } - //continue; - } - } - } - else - { - todo.addAll(curr.getAllSuccessors()); - } - } - - return init; - } - - // Fully clones the reachable graph (i.e. the "general" graph -- cf., EGraph, the specific Scribble concept of an endpoint protocol graph) - protected EState clone(EModelFactory ef) - { - Set all = new HashSet<>(); - all.add(this); - all.addAll(MPrettyState.getReachableStates(this)); - Map map = new HashMap<>(); // original s.id -> clones - for (EState s : all) - { - map.put(s.id, s.cloneNode(ef, s.labs)); - } - for (EState s : all) - { - Iterator as = s.getAllActions().iterator(); - Iterator ss = s.getAllSuccessors().iterator(); - EState clone = map.get(s.id); - while (as.hasNext()) - { - EAction a = as.next(); - EState succ = ss.next(); - clone.addEdge(a, map.get(succ.id)); - } - } - return map.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 (maybe 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 - protected EState unfairClone(EModelFactory ef, EState term, EAction a, EState succ) // Need succ param for non-det - { - //EndpointState succ = take(a); - Set all = new HashSet<>(); - all.add(succ); - all.addAll(MPrettyState.getReachableStates(succ)); - Map map = new HashMap<>(); // original s.id -> clones - for (EState s : all) - { - if (term != null && s.id == term.id) - { - map.put(term.id, term); - } - else - { - //map.put(s.id, newState(s.labs)); - map.put(s.id, s.cloneNode(ef, Collections.emptySet())); // FIXME: remove labs arg from cloneNode and just clear the lab set here? - } - } - for (EState s : all) - { - Iterator as = s.getAllActions().iterator(); - Iterator ss = s.getAllSuccessors().iterator(); - EState clone = map.get(s.id); - while (as.hasNext()) - { - EAction tmpa = as.next(); - EState tmps = ss.next(); - if (s.id != this.id - || (tmpa.equals(a) && tmps.equals(succ))) // Non-det 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? - // ^ Currently, this is like non-fairness is extended to even defeat non-determinism - { - clone.addEdge(tmpa, map.get(tmps.id)); - } - } - } - return map.get(succ.id); - } - - // FIXME: refactor as "isSyncOnly" -- and make an isSync in IOAction - public boolean isConnectOrWrapClientOnly() - { - return getStateKind() == EStateKind.OUTPUT && getAllActions().stream().allMatch((a) -> a.isRequest() || a.isWrapClient()); - } - - public EStateKind getStateKind() - { - List as = this.getAllActions(); - if (as.size() == 0) - { - return EStateKind.TERMINAL; - } - else - { - /*EAction a = as.iterator().next(); - return (a.isSend() || a.isConnect() || a.isDisconnect() || a.isWrapClient() ) ? EStateKind.OUTPUT - //: (a.isConnect() || a.isAccept()) ? Kind.CONNECTION // FIXME: states can have mixed connects and sends - //: (a.isConnect()) ? Kind.CONNECT - : (a.isAccept()) ? EStateKind.ACCEPT // Accept is always unary, guaranteed by treating as a unit message id (wrt. branching) // No: not any more, connect-with-message - : (a.isWrapServer()) ? EStateKind.WRAP_SERVER // WrapServer is always unary, guaranteed by treating as a unit message id (wrt. branching) - : (as.size() > 1) ? EStateKind.POLY_INPUT : EStateKind.UNARY_INPUT;*/ - if (as.stream().allMatch(a -> a.isSend() || a.isRequest() || a.isWrapClient())) // wrapClient should be unary? - { - return EStateKind.OUTPUT; - } - else if (as.stream().allMatch(EAction::isReceive)) - { - return (as.size() == 1) ? EStateKind.UNARY_INPUT : EStateKind.POLY_INPUT; - } - 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).isWrapServer()) - { - return EStateKind.WRAP_SERVER; - } - else - { - throw new RuntimeException("Shouldn't get in here: " + as); - } - } - } - - @Override - public int hashCode() - { - int hash = 83; - hash = 31 * hash + super.hashCode(); // N.B. 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/model/endpoint/EStateKind.java b/scribble-core/src/main/java/org/scribble/model/endpoint/EStateKind.java deleted file mode 100644 index c97d8f19b..000000000 --- a/scribble-core/src/main/java/org/scribble/model/endpoint/EStateKind.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.endpoint; - -// FIXME: consider that enums cannot be "extended" -public enum EStateKind -{ - OUTPUT, // SEND, CONNECT and WRAP_CLIENT - UNARY_INPUT, - POLY_INPUT, - TERMINAL, - ACCEPT, // Unary/multi accept? - WRAP_SERVER, -} diff --git a/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EAccept.java b/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EAccept.java deleted file mode 100644 index 05f5e2227..000000000 --- a/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EAccept.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.endpoint.actions; - -import org.scribble.model.endpoint.EModelFactory; -import org.scribble.model.global.SModelFactory; -import org.scribble.model.global.actions.SAccept; -import org.scribble.type.Payload; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; - -public class EAccept extends EAction -{ - public EAccept(EModelFactory ef, Role peer, MessageId mid, Payload payload) - //public Accept(Role peer) - { - super(ef, peer, mid, payload); - //super(peer, Op.EMPTY_OPERATOR, Payload.EMPTY_PAYLOAD); - } - - @Override - public ERequest toDual(Role self) - { - //return new Connect(self); - return this.ef.newERequest(self, this.mid, this.payload); - } - - @Override - public SAccept toGlobal(SModelFactory sf, Role self) - { - return sf.newSAccept(self, this.peer, this.mid, this.payload); - //return new GAccept(self, this.peer); - } - - @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 EAccept)) - { - return false; - } - return ((EAccept) o).canEqual(this) && super.equals(o); - } - - public boolean canEqual(Object o) - { - return o instanceof EAccept; - } - - @Override - protected String getCommSymbol() - { - return "??"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EAction.java b/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EAction.java deleted file mode 100644 index fc0121252..000000000 --- a/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EAction.java +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.endpoint.actions; - -import org.scribble.model.MAction; -import org.scribble.model.endpoint.EModelFactory; -import org.scribble.model.global.SModelFactory; -import org.scribble.model.global.actions.SAction; -import org.scribble.type.Payload; -import org.scribble.type.kind.Local; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; - -public abstract class EAction extends MAction -{ - public final Role peer; - /*public final MessageId mid; - public final Payload payload; // Empty for MessageSigNames*/ - - protected EModelFactory ef; - - protected EAction(EModelFactory ef, Role peer, MessageId mid, Payload payload) - { - /*this.mid = mid; - this.payload = payload;*/ - super(peer, mid, payload); - this.peer = peer; - - this.ef = ef; - } - - public EModelFactory getEModelFactory() - { - return this.ef; - } - - public abstract EAction toDual(Role self); - - //public abstract GModelAction toGlobal(Role self); - public abstract SAction toGlobal(SModelFactory sf, 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 isWrapClient() - { - return false; - } - - public boolean isWrapServer() - { - 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/model/endpoint/actions/EDisconnect.java b/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EDisconnect.java deleted file mode 100644 index 684129510..000000000 --- a/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EDisconnect.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.endpoint.actions; - -import org.scribble.model.endpoint.EModelFactory; -import org.scribble.model.global.SModelFactory; -import org.scribble.model.global.actions.SDisconnect; -import org.scribble.type.Payload; -import org.scribble.type.name.Op; -import org.scribble.type.name.Role; - -public class EDisconnect extends EAction -{ - public EDisconnect(EModelFactory ef, Role peer) - { - super(ef, peer, Op.EMPTY_OPERATOR, Payload.EMPTY_PAYLOAD); // Must correspond with GDisconnect.UNIT_MESSAGE_SIG_NODE - } - - @Override - public EDisconnect toDual(Role self) - { - return this.ef.newEDisconnect(self); // return this? - } - - @Override - public SDisconnect toGlobal(SModelFactory sf, Role self) - { - return sf.newSDisconnect(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 ((EDisconnect) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof EDisconnect; - } - - @Override - protected String getCommSymbol() - { - //return "\u00A1\u00A1"; - return "-/-"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EReceive.java b/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EReceive.java deleted file mode 100644 index 11b351dc2..000000000 --- a/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EReceive.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.endpoint.actions; - -import org.scribble.model.endpoint.EModelFactory; -import org.scribble.model.global.SModelFactory; -import org.scribble.model.global.actions.SReceive; -import org.scribble.type.Payload; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; - -public class EReceive extends EAction -{ - /*protected static final Set RECEIVES = new HashSet<>(); - - public static Receive get(Role peer, MessageId mid, Payload payload) - { - Receive receive = new Receive(peer, mid, payload, true); - for (Receive r : Receive.RECEIVES) // FIXME: hashmap - { - if (r.equiv(receive)) - { - return r; - } - } - Receive.RECEIVES.add(receive); - return receive; - } - - private Receive(Role peer, MessageId mid, Payload payload, boolean hack) - { - super(peer, mid, payload); - }*/ - - public EReceive(EModelFactory ef, Role peer, MessageId mid, Payload payload) - { - super(ef, peer, mid, payload); - //Receive.RECEIVES.add(this); - } - - @Override - public ESend toDual(Role self) - { - return this.ef.newESend(self, this.mid, this.payload); - //return Send.get(self, this.mid, this.payload); - } - - @Override - //public GModelAction toGlobal(Role self) - public SReceive toGlobal(SModelFactory sf, Role self) - { - //return new GModelAction(this.peer, self, this.mid, this.payload); - ////return GModelAction.get(this.peer, self, this.mid, this.payload); - return sf.newSReceive(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 EReceive)) - { - return false; - } - return ((EReceive) o).canEqual(this) && super.equals(o); - } - - public boolean canEqual(Object o) - { - return o instanceof EReceive; - } - - @Override - protected String getCommSymbol() - { - return "?"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/endpoint/actions/ERequest.java b/scribble-core/src/main/java/org/scribble/model/endpoint/actions/ERequest.java deleted file mode 100644 index 8f371742a..000000000 --- a/scribble-core/src/main/java/org/scribble/model/endpoint/actions/ERequest.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.endpoint.actions; - -import org.scribble.model.endpoint.EModelFactory; -import org.scribble.model.global.SModelFactory; -import org.scribble.model.global.actions.SRequest; -import org.scribble.type.Payload; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; - -public class ERequest extends EAction -{ - public ERequest(EModelFactory ef, Role peer, MessageId mid, Payload payload) - //public Connect(Role peer) - { - super(ef, peer, mid, payload); - //super(peer, Op.EMPTY_OPERATOR, Payload.EMPTY_PAYLOAD); - } - - @Override - public EAccept toDual(Role self) - { - //return new Accept(self); - return this.ef.newEAccept(self, this.mid, this.payload); - } - - @Override - public SRequest toGlobal(SModelFactory sf, Role self) - { - //return new GConnect(self, this.peer); - return sf.newSConnect(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 ERequest)) - { - return false; - } - return ((ERequest) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof ERequest; - } - - @Override - protected String getCommSymbol() - { - return "!!"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/endpoint/actions/ESend.java b/scribble-core/src/main/java/org/scribble/model/endpoint/actions/ESend.java deleted file mode 100644 index fb8176cd6..000000000 --- a/scribble-core/src/main/java/org/scribble/model/endpoint/actions/ESend.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.endpoint.actions; - -import org.scribble.model.endpoint.EModelFactory; -import org.scribble.model.global.SModelFactory; -import org.scribble.model.global.actions.SSend; -import org.scribble.type.Payload; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; - -public class ESend extends EAction -{ - /*protected static final Set SENDS = new HashSet<>(); - - public static Send get(Role peer, MessageId mid, Payload payload) - { - Send send = new Send(peer, mid, payload, true); - for (Send s : Send.SENDS) // FIXME: hashmap - { - if (s.equiv(send)) - { - return s; - } - } - Send.SENDS.add(send); - return send; - } - - public Send(Role peer, MessageId mid, Payload payload, boolean hack) - { - super(peer, mid, payload); - }*/ - - public ESend(EModelFactory ef, Role peer, MessageId mid, Payload payload) - { - super(ef, peer, mid, payload); - //Send.SENDS.add(this); - } - - @Override - public EReceive toDual(Role self) - { - return this.ef.newEReceive(self, this.mid, this.payload); - //return Receive.get(self, this.mid, this.payload); - } - - @Override - //public GModelAction toGlobal(Role self) - public SSend toGlobal(SModelFactory sf, Role self) - { - //return new GModelAction(self, this.peer, this.mid, this.payload); - ////return GModelAction.get(self, this.peer, this.mid, this.payload); - return sf.newSSend(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 ((ESend) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof ESend; - } - - @Override - protected String getCommSymbol() - { - return "!"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EWrapClient.java b/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EWrapClient.java deleted file mode 100644 index 558784b38..000000000 --- a/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EWrapClient.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.endpoint.actions; - -import org.scribble.model.endpoint.EModelFactory; -import org.scribble.model.global.SModelFactory; -import org.scribble.model.global.actions.SWrapClient; -import org.scribble.type.Payload; -import org.scribble.type.name.Op; -import org.scribble.type.name.Role; - -// Duplicated from Disconnect -public class EWrapClient extends EAction -{ - public EWrapClient(EModelFactory ef, Role peer) - { - super(ef, peer, Op.EMPTY_OPERATOR, Payload.EMPTY_PAYLOAD); // Must correspond with GWrap.UNIT_MESSAGE_SIG_NODE - } - - @Override - public EWrapServer toDual(Role self) - { - return this.ef.newEWrapServer(self); - } - - @Override - public SWrapClient toGlobal(SModelFactory sf, Role self) - { - return sf.newSWrapClient(self, this.peer); - } - - @Override - public int hashCode() - { - int hash = 1061; - hash = 31 * hash + super.hashCode(); - return hash; - } - - @Override - public boolean isWrapClient() - { - return true; - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof EWrapClient)) - { - return false; - } - return ((EWrapClient) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof EWrapClient; - } - - @Override - protected String getCommSymbol() - { - return "(!!)"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EWrapServer.java b/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EWrapServer.java deleted file mode 100644 index a45cb32c7..000000000 --- a/scribble-core/src/main/java/org/scribble/model/endpoint/actions/EWrapServer.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.endpoint.actions; - -import org.scribble.model.endpoint.EModelFactory; -import org.scribble.model.global.SModelFactory; -import org.scribble.model.global.actions.SWrapServer; -import org.scribble.type.Payload; -import org.scribble.type.name.Op; -import org.scribble.type.name.Role; - -// Duplicated from Disconnect -public class EWrapServer extends EAction -{ - public EWrapServer(EModelFactory ef, Role peer) - { - super(ef, peer, Op.EMPTY_OPERATOR, Payload.EMPTY_PAYLOAD); // Must correspond with GWrap.UNIT_MESSAGE_SIG_NODE - } - - @Override - public EWrapClient toDual(Role self) - { - return this.ef.newEWrapClient(self); - } - - @Override - public SWrapServer toGlobal(SModelFactory sf, Role self) - { - return sf.newSWrapServer(self, this.peer); - } - - @Override - public int hashCode() - { - int hash = 1063; - hash = 31 * hash + super.hashCode(); - return hash; - } - - @Override - public boolean isWrapServer() - { - return true; - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof EWrapServer)) - { - return false; - } - return ((EWrapServer) o).canEqual(this) && super.equals(o); - } - - public boolean canEqual(Object o) - { - return o instanceof EWrapServer; - } - - @Override - protected String getCommSymbol() - { - return "(??)"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/global/SBuffers.java b/scribble-core/src/main/java/org/scribble/model/global/SBuffers.java deleted file mode 100644 index f8430fca6..000000000 --- a/scribble-core/src/main/java/org/scribble/model/global/SBuffers.java +++ /dev/null @@ -1,342 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.global; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -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.model.endpoint.EModelFactory; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAccept; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.model.endpoint.actions.ERequest; -import org.scribble.model.endpoint.actions.EDisconnect; -import org.scribble.model.endpoint.actions.EReceive; -import org.scribble.model.endpoint.actions.ESend; -import org.scribble.model.endpoint.actions.EWrapClient; -import org.scribble.model.endpoint.actions.EWrapServer; -import org.scribble.type.name.Role; - -public class SBuffers -{ - private final EModelFactory ef; // FIXME: only used by wrapable -- refactor? - - private final Map> connected = new HashMap<>(); - private final Map> buffs = new HashMap<>(); // dest -> src -> msg - - public SBuffers(EModelFactory ef, Set roles, boolean implicit) - { - this(ef, roles); - - if (implicit) - { - roles.forEach((k) -> - { - HashMap tmp = new HashMap<>(); - this.connected.put(k, tmp); - roles.forEach((k2) -> - { - if (!k.equals(k2)) - { - tmp.put(k2, true); - } - }); - }); - } - } - - public SBuffers(EModelFactory ef, Set roles) - { - this.ef = ef; - - // FIXME: do the same for connected - roles.forEach((k) -> - { - HashMap tmp = new HashMap<>(); - this.buffs.put(k, tmp); - roles.forEach((k2) -> - { - if (!k.equals(k2)) - { - tmp.put(k2, null); - } - }); - }); - } - - public SBuffers(SBuffers buffs) - { - this.ef = buffs.ef; - - Set roles = buffs.buffs.keySet(); - roles.forEach((k) -> - { - Map tmp = buffs.connected.get(k); - if (tmp != null) - { - this.connected.put(k, new HashMap<>(tmp)); - } - }); - roles.forEach((k) -> - { - this.buffs.put(k, new HashMap<>(buffs.buffs.get(k))); - }); - } - - // FIXME factor out properly with constructor - public Map> getBuffers() - { - //return this.buffs; - return new SBuffers(this).buffs; - } - - public Map get(Role r) - { - return Collections.unmodifiableMap(this.buffs.get(r)); - } - - /*public boolean isEmpty() - { - return this.buffs.values().stream().flatMap((m) -> m.values().stream()).allMatch((v) -> v == null); - }*/ - public boolean isEmpty(Role r) - { - return this.buffs.get(r).values().stream().allMatch((v) -> v == null); - } - - public boolean isConnected(Role self, Role peer) - { - Map tmp = this.connected.get(self); - if (tmp == null) - { - return false; - } - Boolean b = tmp.get(peer); - return b != null && b; - } - - public boolean canAccept(Role self, EAccept a) - //public boolean canAccept(Role r1, Role r2) - { - return !isConnected(self, a.peer); - //return canConnect(r2, r1); - } - - public boolean canConnect(Role self, ERequest c) - //public boolean canConnect(Role r1, Role r2) - { - return !isConnected(self, c.peer); - //return !isConnected(r1, r2); - } - - public boolean canDisconnect(Role self, EDisconnect d) - { - return isConnected(self, d.peer); - } - - public boolean canWrapClient(Role self, EWrapClient wc) - { - return isConnected(self, wc.peer); - } - - public boolean canWrapServer(Role self, EWrapServer ws) - { - return isConnected(self, ws.peer); - } - - //public WFBuffers connect(Role src, Connect c, Role dest) - public SBuffers connect(Role src, Role dest) - { - SBuffers copy = new SBuffers(this); - Map tmp1 = copy.connected.get(src); - if (tmp1 == null) - { - tmp1 = new HashMap<>(); - copy.connected.put(src, tmp1); - } - tmp1.put(dest, true); - Map tmp2 = copy.connected.get(dest); - if (tmp2 == null) - { - tmp2 = new HashMap<>(); - copy.connected.put(dest, tmp2); - } - tmp2.put(src, true); - //copy.buffs.get(c.peer).put(src, new Send(c.peer, c.mid, c.payload)); - return copy; - } - - public SBuffers disconnect(Role self, EDisconnect d) - { - SBuffers copy = new SBuffers(this); - copy.connected.get(self).put(d.peer, false); - return copy; - } - - public boolean canSend(Role self, ESend a) - { - return isConnected(self, a.peer) && (this.buffs.get(a.peer).get(self) == null); - } - - public SBuffers send(Role self, ESend a) - { - SBuffers copy = new SBuffers(this); - copy.buffs.get(a.peer).put(self, a); - return copy; - } - - /*public boolean canReceive(Role self, Receive a) - { - Send send = this.buffs.get(self).get(a.peer); - return send != null && send.toDual(a.peer).equals(a); - }*/ - - //public Set receivable(Role r) - public Set inputable(Role r) // FIXME: IAction // FIXME: OAction version? - { - /*Map tmp = this.connected.get(r); - if (tmp == null) - { - return Collections.emptySet(); // Not needed, guarded by state kind - }*/ - Set res = this.buffs.get(r).entrySet().stream() - .filter(e -> e.getValue() != null) - .map(e -> e.getValue().toDual(e.getKey())) - .collect(Collectors.toSet()); - /*Map tmp = this.connected.get(r); - if (tmp == null) - { - this.buffs.get(r).keySet().forEach((x) -> res.add(new Accept(x))); - } - else - { - this.connected.keySet().stream() - .filter((k) -> !tmp.containsKey(k) || !tmp.get(k)) - .forEach((k) -> res.add(new Accept(k))); - }*/ - return res; - } - - //public Set acceptable(Role r) // Means connection accept actions - // Pre: curr is Accept state, r is accept peer - public Set acceptable(Role r, EState curr) // Means connection accept actions - { - Set res = new HashSet<>(); - Map tmp = this.connected.get(r); - /*if (tmp == null) - { - this.buffs.get(r).keySet().forEach((x) -> res.add(new Accept(x))); - } - else - { - this.connected.keySet().stream() - .filter((k) -> !tmp.containsKey(k) || !tmp.get(k)) - .forEach((k) -> res.add(new Accept(k))); - }*/ - if (tmp != null) - { - Boolean b = tmp.get(r); - if (b != null && b) - { - return res; - } - } - List as = curr.getAllActions(); - for (EAction a : as) - { - res.add((EAccept) a); - } - return res; - } - - public Set wrapable(Role r) - { - Set res = new HashSet<>(); - Map tmp = this.connected.get(r); - if (tmp != null) - { - this.connected.keySet().stream() - .filter(k -> tmp.containsKey(k) && tmp.get(k)) - .forEach(k -> res.add(this.ef.newEWrapServer(k))); - } - return res; - } - - /*//public Map receivable() - public Map inputable() - { - //Map tmp = new HashMap<>(); - Map tmp = new HashMap<>(); - for (Role r : this.buffs.keySet()) - { - Map tmp2 = this.buffs.get(r); - for (Role r2: tmp2.keySet()) - { - tmp.put(r, tmp2.get(r2).toDual(r2)); - } - } - return tmp; - }*/ - - public SBuffers receive(Role self, EReceive a) - { - SBuffers copy = new SBuffers(this); - copy.buffs.get(self).put(a.peer, null); - return copy; - } - - @Override - public final int hashCode() - { - int hash = 131; - hash = 31 * hash + this.buffs.hashCode(); - hash = 31 * hash + this.connected.hashCode(); - return hash; - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof SBuffers)) - { - return false; - } - SBuffers b = (SBuffers) o; - return this.buffs.equals(b.buffs) && this.connected.equals(b.connected); - } - - @Override - public String toString() - { - //return this.buffs.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()))) // Inference not working? - .collect(Collectors.toMap((Entry f) -> f.getKey(), (f) -> f.getValue()))) - )).toString(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/global/SConfig.java b/scribble-core/src/main/java/org/scribble/model/global/SConfig.java deleted file mode 100644 index b9f51df03..000000000 --- a/scribble-core/src/main/java/org/scribble/model/global/SConfig.java +++ /dev/null @@ -1,805 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.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.Set; -import java.util.stream.Collectors; - -import org.scribble.model.endpoint.EFSM; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.EStateKind; -import org.scribble.model.endpoint.actions.EAccept; -import org.scribble.model.endpoint.actions.ERequest; -import org.scribble.model.endpoint.actions.EDisconnect; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.model.endpoint.actions.EReceive; -import org.scribble.model.endpoint.actions.ESend; -import org.scribble.model.endpoint.actions.EWrapClient; -import org.scribble.model.endpoint.actions.EWrapServer; -import org.scribble.type.name.Role; - -public class SConfig -{ - protected final SModelFactory sf; - - //public final Map states; - public final Map efsms; - public final SBuffers buffs; - - //public WFConfig(Map state, Map> buff) - //public WFConfig(Map state, WFBuffers buffs) - protected SConfig(SModelFactory sf, Map state, SBuffers buffs) - { - this.sf = sf; - - this.efsms = Collections.unmodifiableMap(state); - //this.buffs = Collections.unmodifiableMap(buff.keySet().stream() .collect(Collectors.toMap((k) -> k, (k) -> Collections.unmodifiableMap(buff.get(k))))); - //this.buffs = Collections.unmodifiableMap(buff); - this.buffs = buffs; - } - - // FIXME: rename: not just termination, could be unconnected/uninitiated - //public boolean isEnd() - public boolean isSafeTermination() - { - //return this.states.values().stream().allMatch((s) -> s.isTerminal()) && this.buffs.isEmpty(); - for (Role r : this.efsms.keySet()) - { - if (!canSafelyTerminate(r)) - { - return false; - } - } - return true; - } - - // Should work both with and without accept-correlation? - public boolean canSafelyTerminate(Role r) - { - //EndpointState s = this.states.get(r); - EFSM s = this.efsms.get(r); - //return - /*boolean cannotSafelyTerminate = // FIXME: check and cleanup - (s.isTerminal() && !this.buffs.isEmpty(r)) - || - (!s.isTerminal() && - //(!(s.getStateKind().equals(Kind.UNARYINPUT) && s.getTakeable().iterator().next().isAccept()) // Accept state now distinguished - ( - !(s.getStateKind().equals(Kind.ACCEPT) && s.isInitial()) // FIXME: check stable - // FIXME: needs initial state check -- although if there is an accept, there should a connect, and waitfor-errors checked via connects) -- this should be OK because connect/accept are sync -- but not fully sufficient by itself, see next - // So could be blocked on unary accept part way through the protocol -- but also could be unfolded initial accept - ////|| this.states.keySet().stream().anyMatch((rr) -> !r.equals(rr) && this.buffs.isConnected(r, rr)))) - //&& this.states.keySet().stream().anyMatch((rr) -> !r.equals(rr) && this.buffs.isConnected(r, rr)) - // FIXME: isConnected is not symmetric, and could disconnect all part way through protocol -- but can't happen? - // Above assumes initial is not terminal (holds for EFSMs), and doesn't check buffer is empty (i.e. for orphan messages) - ) - ) - || - (!s.isTerminal() && this.states.keySet().stream().anyMatch((rr) -> !r.equals(rr) && this.buffs.isConnected(r, rr))) - ;*/ - //return !cannotSafelyTerminate; - boolean canSafelyTerminate = - (s.isTerminated() && this.buffs.isEmpty(r)) - || (s.getStateKind().equals(EStateKind.ACCEPT) && s.isInitial()) // FIXME: should be empty buffs - - // FIXME: 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.buffs.isConnected(r, rr))) - ; - return canSafelyTerminate; - } - - public List fire(Role r, EAction a) - { - List res = new LinkedList<>(); - - //List succs = this.states.get(r).takeAll(a); - List succs = this.efsms.get(r).fireAll(a); - //for (EndpointState succ : succs) - for (EFSM succ : succs) - { - //Map tmp1 = new HashMap<>(this.states); - Map tmp1 = new HashMap<>(this.efsms); - //Map> tmp2 = new HashMap<>(this.buffs); - - tmp1.put(r, succ); - - /*Map tmp3 = new HashMap<>(tmp2.get(a.peer)); - tmp2.put(a.peer, tmp3);* / - Map tmp3 = tmp2.get(a.peer); - if (a.isSend()) - { - tmp3.put(r, (Send) a); - } - else - { - tmp3.put(r, null); - }*/ - SBuffers tmp2 = - a.isSend() ? this.buffs.send(r, (ESend) a) - : a.isReceive() ? this.buffs.receive(r, (EReceive) a) - : a.isDisconnect() ? this.buffs.disconnect(r, (EDisconnect) a) - : null; - if (tmp2 == null) - { - throw new RuntimeException("Shouldn't get in here: " + a); - } - res.add(this.sf.newSConfig(tmp1, tmp2)); - } - - return res; - } - - public List sync(Role r1, EAction a1, Role r2, EAction a2) - { - List res = new LinkedList<>(); - - /*List succs1 = this.states.get(r1).takeAll(a1); - List succs2 = this.states.get(r2).takeAll(a2); - for (EndpointState succ1 : succs1)*/ - List succs1 = this.efsms.get(r1).fireAll(a1); - List succs2 = this.efsms.get(r2).fireAll(a2); - for (EFSM succ1 : succs1) - { - //for (EndpointState succ2 : succs2) - for (EFSM succ2 : succs2) - { - //Map tmp1 = new HashMap<>(this.states); - Map tmp1 = new HashMap<>(this.efsms); - tmp1.put(r1, succ1); - tmp1.put(r2, succ2); - SBuffers tmp2; - if (((a1.isRequest() && a2.isAccept()) || (a1.isAccept() && a2.isRequest()))) - //&& this.buffs.canConnect(r1, r2)) - { - tmp2 = this.buffs.connect(r1, r2); - } - else if (((a1.isWrapClient() && a2.isWrapServer()) || (a1.isWrapServer() && a2.isWrapClient()))) - { - tmp2 = this.buffs; // OK, immutable? - } - else - { - throw new RuntimeException("Shouldn't get in here: " + a1 + ", " + a2); - } - res.add(this.sf.newSConfig(tmp1, tmp2)); - } - } - - return res; - } - - // Deadlock from non handle-able messages (reception errors) - public Map getStuckMessages() - { - Map res = new HashMap<>(); - for (Role r : this.efsms.keySet()) - { - //EndpointState s = this.states.get(r); - EFSM s = this.efsms.get(r); - EStateKind k = s.getStateKind(); - if (k == EStateKind.UNARY_INPUT || k == EStateKind.POLY_INPUT) - { - /*Set duals = this.buffs.get(r).entrySet().stream() - .filter((e) -> e.getValue() != null) - .map((e) -> e.getValue().toDual(e.getKey())) - .collect(Collectors.toSet()); - if (duals.stream().anyMatch((a) -> s.isAcceptable(a))) - { - break; - }*/ - Role peer = s.getAllFireable().iterator().next().peer; - ESend send = this.buffs.get(r).get(peer); - if (send != null) - { - EReceive recv = send.toDual(peer); - if (!s.hasFireable(recv)) - //res.put(r, new IOError(peer)); - res.put(r, recv); - } - } - /*else if (k == Kind.ACCEPT) // FIXME: ..and connect - { - // FIXME: issue is, unlike regular input states, blocked connect/accept may become unblocked later, so queued messages may not 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) -- i.e. only "bad" deadlocks - public Set> getWaitForErrors() - { - Set> res = new HashSet<>(); - List todo = new LinkedList<>(this.efsms.keySet()); - /*while (!todo.isEmpty()) - { - Role r = todo.get(0); - todo.remove(r); - Set seen = new HashSet<>(); - while (true) - { - if (seen.contains(r)) - { - res.add(seen); - break; - } - seen.add(r); - Role rr = isInputBlocked(r); - if (rr == null) - { - break; - } - todo.remove(rr); - if (this.states.get(rr).isTerminal()) - { - seen.add(rr); - res.add(seen); - break; - } - r = rr; - } - }*/ - while (!todo.isEmpty()) // FIXME: maybe better to do directly on states, rather than via roles - { - Role r = todo.remove(0); - //Set cycle = isCycle(new HashSet<>(), new HashSet<>(Arrays.asList(r))); - if (!this.efsms.get(r).isTerminated()) - { - Set cycle = isWaitForChain(r); - //if (!cycle.isEmpty()) - if (cycle != null) - { - todo.removeAll(cycle); - res.add(cycle); - } - } - } - return res; - } - - // Includes dependencies from input-blocking, termination and connect-blocking - // FIXME: should also include connect? - // NB: if this.states.get(orig).isTerminal() then orig is returned as "singleton deadlock" - //public Set isCycle(Set candidate, Set todo) - public Set isWaitForChain(Role orig) - { - /*if (todo.isEmpty()) - { - return candidate; - }*/ - /*Set tmp = new HashSet(todo); - Role r = tmp.iterator().next(); - tmp.remove(r); - candidate.add(r);*/ - Set candidate = new LinkedHashSet<>(); - Set todo = new LinkedHashSet<>(Arrays.asList(orig)); - while (!todo.isEmpty()) - { - Role r = todo.iterator().next(); - todo.remove(r); - candidate.add(r); - - //EndpointState s = this.states.get(r); - EFSM s = this.efsms.get(r); - - if (s == null) - { - System.out.println("AAA: " + this.efsms + ", " + r); - } - - if (s.getStateKind() == EStateKind.OUTPUT && !s.isConnectOrWrapClientOnly()) // FIXME: includes connect, could still be deadlock? -- no: doesn't include connect any more - { - // FIXME: move into isWaitingFor - return null; - } - if (s.isTerminated()) - { - if (todo.isEmpty()) - { - return candidate; - } - continue; - } - Set blocked = isWaitingFor(r); - //if (blocked.isEmpty()) - if (blocked == null) - { - return null; - } - if (todo.isEmpty() && candidate.containsAll(blocked)) - { - return candidate; - } - blocked.forEach((x) -> - { - if (!candidate.contains(x)) - { - //candidate.add(x); - todo.add(x); - } - }); - } - return null; - } - - // Generalised to include connect-blocked roles - //private Role isInputBlocked(Role r) - private Set isWaitingFor(Role r) - { - //EndpointState s = this.states.get(r); - EFSM s = this.efsms.get(r); - EStateKind k = s.getStateKind(); - if (k == EStateKind.UNARY_INPUT || k == EStateKind.POLY_INPUT) - { - List all = s.getAllFireable(); - EAction a = all.get(0); // FIXME: assumes single choice subject (OK for current syntax, but should generalise) - /*if (a.isAccept()) // Sound? - { - return null; - }*/ - /*Role peer = a.peer; - if (a.isReceive() && this.buffs.get(r).get(peer) == null) - { - //return peer; - }*/ - if (a.isReceive()) - { - Set peers = all.stream().map((x) -> x.peer).collect(Collectors.toSet()); - if (peers.stream().noneMatch((p) -> this.buffs.get(r).get(p) != null)) - { - return peers; - } - /*Set peers = new HashSet<>(); // Debugging AllTest/BadTest bad.efsm.grecursion.unfair.Test01; problem - for (EAction ea : all) - { - peers.add(ea.peer); - } - boolean tmp = true; - for (Role p : peers) - { - if (this.buffs.get(r).get(p) != null) - { - tmp = false; - break; - } - } - if (tmp) - { - return peers; - }*/ - } - } - else if (k == EStateKind.ACCEPT) - { - // FIXME TODO: if analysing ACCEPTs, check if s is initial (not "deadlock blocked" if initial) -- no: instead, analysing connects - if (!s.isInitial()) - { - List all = s.getAllFireable(); // Should be singleton -- no: not any more - /*Set rs = all.stream().map((x) -> x.peer).collect(Collectors.toSet()); - if (rs.stream().noneMatch((x) -> this.states.get(x).getAllTakeable().contains(new Connect(r)))) // cf. getTakeable - //if (peera.equals(c.toDual(r)) && this.buffs.canConnect(r, c)) - { - return rs; - }*/ - Set res = new HashSet(); - for (EAction a : all) // Accept // FIXME: WrapServer - { - if (this.efsms.get(a.peer).getAllFireable().contains(a.toDual(r))) - { - return null; - } - res.add(a.peer); - } - if (!res.isEmpty()) - { - return res; - } - } - } - //else if (k == Kind.CONNECTION) - else if (k == EStateKind.OUTPUT //|| k == Kind.ACCEPT ..// FIXME: check connects if no available sends - ) - { - //List all = s.getAllAcceptable(); - if (s.isConnectOrWrapClientOnly()) - { - List all = s.getAllFireable(); - /*Set peers = all.stream().map((x) -> x.peer).collect(Collectors.toSet()); // Should be singleton by enabling conditions - if (peers.stream().noneMatch((p) -> this.states.get(p).getAllTakeable().contains(new Accept(r)))) // cf. getTakeable - { - return peers; - }*/ - Set res = new HashSet(); - for (EAction a : all) // Connect or WrapClient - { - if (this.efsms.get(a.peer).getAllFireable().contains(a.toDual(r))) - { - return null; - } - res.add(a.peer); - } - if (!res.isEmpty()) - { - return res; - } - } - } - return null; - //return Collections.emptySet(); - } - - // Generalised to include "unconnected" messages -- should unconnected messages be treated via stuck instead? - public Map> getOrphanMessages() - { - Map> res = new HashMap<>(); - for (Role r : this.efsms.keySet()) - { - //EndpointState s = this.states.get(r); - EFSM s = this.efsms.get(r); - if (s.isTerminated()) // Local termination of r, i.e. not necessarily "full deadlock" - { - Set orphs = this.buffs.get(r).values().stream().filter((v) -> v != null).collect(Collectors.toSet()); - if (!orphs.isEmpty()) - { - Set tmp = res.get(r); - if (tmp == null) - { - tmp = new HashSet<>(); - res.put(r, tmp); - } - tmp.addAll(orphs); - } - } - else - { - this.efsms.keySet().forEach((rr) -> - { - if (!rr.equals(r)) - { - // Connection direction doesn't matter? -- wrong: matters because of async. disconnect - if (!this.buffs.isConnected(r, rr)) - { - ESend send = this.buffs.get(r).get(rr); - if (send != null) - { - Set tmp = res.get(r); - if (tmp == null) - { - tmp = new HashSet<>(); - res.put(r, tmp); - } - tmp.add(send); - } - } - } - }); - } - } - 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() - { - Map res = new HashMap<>(); - if (getFireable().isEmpty() && !isSafeTermination()) - { - for (Role r : this.efsms.keySet()) - { - if (!canSafelyTerminate(r)) - { - res.put(r, this.efsms.get(r).curr); - } - } - } - return res; - } - - public Map> getFireable() - { - Map> res = new HashMap<>(); - for (Role r : this.efsms.keySet()) - { - //EndpointState s = this.states.get(r); - EFSM fsm = this.efsms.get(r); - switch (fsm.getStateKind()) // Choice subject enabling needed for non-mixed states (mixed states would be needed for async. permutations though) - { - case OUTPUT: - { - List as = fsm.getAllFireable(); - for (EAction a : as) - { - if (a.isSend()) - { - if (this.buffs.canSend(r, (ESend) a)) - { - List tmp = res.get(r); // FIXME: factor out - if (tmp == null) - { - tmp = new LinkedList<>(); - res.put(r, tmp); - } - tmp.add(a); - } - } - else if (a.isRequest()) - { - // FIXME: factor out - ERequest c = (ERequest) a; - //EndpointState speer = this.states.get(c.peer); - EFSM speer = this.efsms.get(c.peer); - //if (speer.getStateKind() == Kind.UNARY_INPUT) - { - List peeras = speer.getAllFireable(); - for (EAction peera : peeras) - { - if (peera.equals(c.toDual(r)) && this.buffs.canConnect(r, c)) // Cf. isWaitingFor - { - List tmp = res.get(r); - if (tmp == null) - { - tmp = new LinkedList<>(); - res.put(r, tmp); - } - tmp.add(a); - } - } - } - } - else if (a.isDisconnect()) - { - // Duplicated from Send - if (this.buffs.canDisconnect(r, (EDisconnect) a)) - { - List tmp = res.get(r); // FIXME: factor out - if (tmp == null) - { - tmp = new LinkedList<>(); - res.put(r, tmp); - } - tmp.add(a); - } - } - else if (a.isWrapClient()) - { - // FIXME: factor out - EWrapClient wc = (EWrapClient) a; - EFSM speer = this.efsms.get(wc.peer); - List peeras = speer.getAllFireable(); - for (EAction peera : peeras) - { - if (peera.equals(wc.toDual(r)) && this.buffs.canWrapClient(r, wc)) // Cf. isWaitingFor - { - List tmp = res.get(r); - if (tmp == null) - { - tmp = new LinkedList<>(); - res.put(r, tmp); - } - tmp.add(a); - } - } - } - else - { - throw new RuntimeException("Shouldn't get in here: " + a); - } - } - break; - } - case UNARY_INPUT: - case POLY_INPUT: - { - for (EAction a : this.buffs.inputable(r)) - { - if (a.isReceive()) - { - if (fsm.hasFireable(a)) - { - List tmp = res.get(r); - if (tmp == null) - { - tmp = new LinkedList<>(); - res.put(r, tmp); - } - tmp.add(a); - } - } - /*else if (a.isAccept()) - { - // FIXME: factor out - Accept c = (Accept) a; - EndpointState speer = this.states.get(c.peer); - //if (speer.getStateKind() == Kind.OUTPUT) - { - List peeras = speer.getAllAcceptable(); - for (IOAction peera : peeras) - { - if (peera.equals(c.toDual(r)) && this.buffs.canAccept(r, c)) - { - List tmp = res.get(r); - if (tmp == null) - { - tmp = new LinkedList<>(); - res.put(r, tmp); - } - tmp.add(a); - //break; // Add all of them - } - } - } - }*/ - else - { - throw new RuntimeException("Shouldn't get in here: " + a); - } - } - break; - } - case TERMINAL: - { - break; - } - /*case CONNECT: - { - List as = s.getAllTakeable(); - for (IOAction a : as) - { - if (a.isConnect()) ..// FIXME: could be send actions - { - // FIXME: factor out - Connect c = (Connect) a; - EndpointState speer = this.states.get(c.peer); - //if (speer.getStateKind() == Kind.UNARY_INPUT) - { - List peeras = speer.getAllTakeable(); - for (IOAction peera : peeras) - { - if (peera.equals(c.toDual(r)) && this.buffs.canConnect(r, c)) - { - List tmp = res.get(r); - if (tmp == null) - { - tmp = new LinkedList<>(); - res.put(r, tmp); - } - tmp.add(a); - } - } - } - } - else - { - throw new RuntimeException("Shouldn't get in here: " + s); - } - } - break; - }*/ - case ACCEPT: - { - for (EAction a : this.buffs.acceptable(r, fsm.curr)) - { - if (a.isAccept()) - { - // FIXME: factor out - EAccept c = (EAccept) a; - //EndpointState speer = this.states.get(c.peer); - EFSM speer = this.efsms.get(c.peer); - //if (speer.getStateKind() == Kind.OUTPUT) - { - List peeras = speer.getAllFireable(); - for (EAction peera : peeras) - { - if (peera.equals(c.toDual(r)) && this.buffs.canAccept(r, c)) - { - List tmp = res.get(r); - if (tmp == null) - { - tmp = new LinkedList<>(); - res.put(r, tmp); - } - tmp.add(a); - //break; // Add all of them - } - } - } - } - else - { - throw new RuntimeException("Shouldn't get in here: " + a); - } - } - break; - } - case WRAP_SERVER: - { - for (EAction a : this.buffs.wrapable(r)) - { - if (a.isWrapServer()) - { - EWrapServer ws = (EWrapServer) a; - EFSM speer = this.efsms.get(ws.peer); - { - List peeras = speer.getAllFireable(); - for (EAction peera : peeras) - { - if (peera.equals(ws.toDual(r)) && this.buffs.canWrapServer(r, ws)) - { - List tmp = res.get(r); - if (tmp == null) - { - tmp = new LinkedList<>(); - res.put(r, tmp); - } - tmp.add(a); - } - } - } - } - else - { - throw new RuntimeException("Shouldn't get in here: " + a); - } - } - break; - } - default: - { - throw new RuntimeException("Shouldn't get in here: " + fsm); - } - } - } - return res; - } - - @Override - public int hashCode() - { - int hash = 71; - hash = 31 * hash + this.efsms.hashCode(); - hash = 31 * hash + this.buffs.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.buffs.equals(c.buffs); - } - - @Override - public String toString() - { - return "(" + this.efsms + ", " + this.buffs + ")"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/global/SGraph.java b/scribble-core/src/main/java/org/scribble/model/global/SGraph.java deleted file mode 100644 index 5795cb7e1..000000000 --- a/scribble-core/src/main/java/org/scribble/model/global/SGraph.java +++ /dev/null @@ -1,259 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.global; - -import java.util.Collections; -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.SortedMap; -import java.util.TreeMap; - -import org.scribble.model.MPrettyPrint; -import org.scribble.model.global.actions.SAction; -import org.scribble.type.name.GProtocolName; - -public class SGraph implements MPrettyPrint -{ - public final GProtocolName proto; - //private final Map efsms; - //private final boolean fair; - - public final SState init; - public Map states; // State ID -> GMState - - private Map> reach; // State ID -> reachable states (not reflexive) - private Set> termSets; - - // Unlike EState, SGraph is not just a "simple wrapper" for an existing graph of nodes -- it is a "semantic structure" that needs to be fully built properly (so no arbitrary "toGraph" method; cf., EState) - protected SGraph(GProtocolName proto, Map states, SState init) - { - this.proto = proto; - this.init = init; - this.states = Collections.unmodifiableMap(states); - this.reach = getReachabilityMap(); - } - - /*public SModel toModel() - { - return new SModel(this); - }*/ - - 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); - Set tmp = new HashSet<>(rs); - tmp.remove(s.id); - for (Integer r : tmp) - { - if (!this.reach.containsKey(r) || !this.reach.get(r).equals(rs)) - { - return false; - } - } - return true; - } - - // Pre: reach.get(start).contains(end) // FIXME: will return null if initial - // state is error - public List getTrace(SState start, SState end) - { - SortedMap> candidates = new TreeMap<>(); - Set dis0 = new HashSet(); - 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.getAllActions().iterator(); - Iterator ss = curr.getAllSuccessors().iterator(); - while (as.hasNext()) - { - SAction a = as.next(); - SState s = ss.next(); - if (s.id == end.id) - { - trace.add(a); - return trace; - } - - if (!seen.contains(s.id) && this.reach.containsKey(s.id) - && this.reach.get(s.id).contains(end.id)) - { - seen.add(s.id); - Set tmp1 = candidates.get(dis + 1); - if (tmp1 == null) - { - tmp1 = new HashSet<>(); - candidates.put(dis + 1, tmp1); - } - tmp1.add(s.id); - List tmp2 = new LinkedList<>(trace); - tmp2.add(a); - List res = getTraceAux(tmp2, seen, candidates, end); - if (res != null) - { - return res; - } - } - } - return null; - } - - // 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).getAllSuccessors()) - { - 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); - } - - @Override - public String toDot() - { - return this.init.toDot(); - } - - @Override - public String toAut() - { - return this.init.toAut(); - } - - @Override - public String toString() - { - return this.init.toString(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/global/SGraphBuilderUtil.java b/scribble-core/src/main/java/org/scribble/model/global/SGraphBuilderUtil.java deleted file mode 100644 index 0d9d099c6..000000000 --- a/scribble-core/src/main/java/org/scribble/model/global/SGraphBuilderUtil.java +++ /dev/null @@ -1,235 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.global; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.stream.Collectors; - -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.model.GraphBuilderUtil; -import org.scribble.model.endpoint.EFSM; -import org.scribble.model.endpoint.EGraph; -import org.scribble.model.endpoint.EModelFactory; -import org.scribble.model.endpoint.EStateKind; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.model.global.actions.SAction; -import org.scribble.type.kind.Global; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.Role; - -public class SGraphBuilderUtil extends GraphBuilderUtil -{ - public final SModelFactory sf; - - protected SGraphBuilderUtil(SModelFactory sf) - { - this.sf = sf; - //reset(); - init(sf.newSState(null)); - } - - // N.B. must be called before every "new visit", including first - @Override - public void init(SState init) - { - //init(this.sf.newSState(null), this.sf.newSState(null)); // configs - reset(init, this.sf.newSState(null)); - } - - // Do as an initial state rather than config? - protected SConfig createInitialSConfig(EModelFactory ef, Map egraphs, boolean explicit) // FIXME: ef - { - Map efsms = egraphs.entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> e.getValue().toFsm())); - SBuffers b0 = new SBuffers(ef, efsms.keySet(), !explicit); - //return job.sf.newSConfig(efsms, b0); - return this.sf.newSConfig(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 buildSGraph(Job job, GProtocolName fullname, SConfig c0) throws ScribbleException - public SGraph buildSGraph(Job job, GProtocolName fullname, Map egraphs, boolean explicit) throws ScribbleException - { - /*Map efsms = egraphs.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().toFsm())); - - SBuffers b0 = new SBuffers(job.ef, efsms.keySet(), !explicit);*/ - - //SConfig c0 = job.sf.newSConfig(efsms, b0); - SConfig c0 = createInitialSConfig(job.ef, egraphs, explicit); - - SState init = job.sf.newSState(c0); - - Map seen = new HashMap<>(); - LinkedHashSet todo = new LinkedHashSet<>(); - todo.add(init); - - // FIXME: factor out model building and integrate with getAllNodes (seen == all) - int count = 0; - while (!todo.isEmpty()) - { - Iterator i = todo.iterator(); - SState curr = i.next(); - i.remove(); - seen.put(curr.id, curr); - - if (job.debug) - { - count++; - if (count % 50 == 0) - { - job.debugPrintln("(" + fullname + ") Building global states: " + count); - } - } - - Map> fireable = curr.getFireable(); - - //job.debugPrintln("Acceptable at (" + curr.id + "): " + fireable); - - for (Role r : fireable.keySet()) - { - List fireable_r = fireable.get(r); - - // Hacky? // FIXME: factor out and make more robust (e.g. for new state kinds) -- e.g. "hasPayload" in IOAction - //EndpointState currstate = curr.config.states.get(r); - EFSM currfsm = curr.config.efsms.get(r); - EStateKind k = currfsm.getStateKind(); - if (k == EStateKind.OUTPUT) - { - for (EAction a : fireable_r) // Connect implicitly has no payload (also accept, so skip) - { - if (fireable_r.stream().anyMatch((x) -> - !a.equals(x) && a.peer.equals(x.peer) && a.mid.equals(x.mid) && !a.payload.equals(x.payload))) - { - throw new ScribbleException("Bad non-deterministic action payloads: " + fireable_r); - } - } - } - else if (k == EStateKind.UNARY_INPUT || k == EStateKind.POLY_INPUT || k == EStateKind.ACCEPT) - { - for (EAction a : fireable_r) - { - if (currfsm.getAllFireable().stream().anyMatch((x) -> - !a.equals(x) && a.peer.equals(x.peer) && a.mid.equals(x.mid) && !a.payload.equals(x.payload))) - { - throw new ScribbleException("Bad non-deterministic action payloads: " + currfsm.getAllFireable()); - } - } - } - } // Need to do all action payload checking before next building step, because doing sync actions will also remove peer's actions from takeable set - - for (Role r : fireable.keySet()) - { - List fireable_r = fireable.get(r); - - for (EAction a : fireable_r) - { - if (a.isSend() || a.isReceive() || a.isDisconnect()) - { - getNextStates(job.sf, todo, seen, curr, a.toGlobal(job.sf, r), curr.fire(r, a)); - } - else if (a.isAccept() || a.isRequest()) - { - List as = fireable.get(a.peer); - EAction d = a.toDual(r); - if (as != null && as.contains(d)) - { - as.remove(d); // Removes one occurrence - //getNextStates(seen, todo, curr.sync(r, a, a.peer, d)); - SAction g = (a.isRequest()) ? a.toGlobal(job.sf, r) : d.toGlobal(job.sf, a.peer); // 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) - getNextStates(job.sf, todo, seen, curr, g, curr.sync(r, a, a.peer, d)); - } - } - else if (a.isWrapClient() || a.isWrapServer()) - { - List as = fireable.get(a.peer); - EAction w = a.toDual(r); - if (as != null && as.contains(w)) - { - as.remove(w); // Removes one occurrence - SAction g = (a.isRequest()) ? a.toGlobal(job.sf, r) : w.toGlobal(job.sf, a.peer); - getNextStates(job.sf, todo, seen, curr, g, curr.sync(r, a, a.peer, w)); - } - } - else - { - throw new RuntimeException("Shouldn't get in here: " + a); - } - } - } - } - - SGraph graph = job.sf.newSGraph(fullname, seen, init); - - job.debugPrintln("(" + fullname + ") Built global model..\n" + graph.init.toDot() + "\n(" + fullname + ") .." + graph.states.size() + " states"); - - return graph; - } - - private void getNextStates(SModelFactory sf, LinkedHashSet todo, - Map seen, SState curr, SAction a, List nexts) - { - for (SConfig next : nexts) - { - SState news = sf.newSState(next); - SState succ = null; - //if (seen.contains(succ)) // FIXME: make a SGraph builder - /*if (seen.containsValue(succ)) - { - for (WFState tmp : seen) - { - if (tmp.equals(succ)) - { - succ = tmp; - } - } - }*/ - for (SState tmp : seen.values()) // Key point: checking "semantically" if model state already created - { - if (tmp.equals(news)) - { - succ = tmp; - } - } - if (succ == null) - { - for (SState tmp : todo) // If state created but not "seen" yet, then it will be "todo" - { - if (tmp.equals(news)) - { - succ = tmp; - } - } - } - if (succ == null) - { - succ = news; - todo.add(succ); - } - //curr.addEdge(a.toGlobal(r), succ); - curr.addEdge(a, succ); // FIXME: make a Builder util, cf. EGraphBuilderUtil - //if (!seen.contains(succ) && !todo.contains(succ)) - /*if (!seen.containsKey(succ.id) && !todo.contains(succ)) - { - todo.add(succ); - }*/ - } - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/global/SModel.java b/scribble-core/src/main/java/org/scribble/model/global/SModel.java deleted file mode 100644 index 7d59aa197..000000000 --- a/scribble-core/src/main/java/org/scribble/model/global/SModel.java +++ /dev/null @@ -1,253 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.global; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.model.endpoint.EFSM; -import org.scribble.model.endpoint.actions.ESend; -import org.scribble.model.global.actions.SAction; -import org.scribble.type.name.Role; - -public class SModel -{ - public final SGraph graph; - - protected SModel(SGraph graph) - { - this.graph = graph; - } - - public void validate(Job job) throws ScribbleException - { - SState init = this.graph.init; - Map states = this.graph.states; - - String errorMsg = ""; - - int count = 0; - for (SState s : states.values()) - { - if (job.debug) - { - count++; - if (count % 50 == 0) - { - //job.debugPrintln("(" + this.graph.proto + ") Checking safety: " + count + " states"); - job.debugPrintln("(" + this.graph.proto + ") Checking states: " + count); - } - } - SStateErrors errors = s.getErrors(); - if (!errors.isEmpty()) - { - // FIXME: getTrace can get stuck when local choice subjects are disabled - List trace = this.graph.getTrace(init, s); // FIXME: getTrace broken on non-det self loops? - //errorMsg += "\nSafety violation(s) at " + s.toString() + ":\n Trace=" + trace; - errorMsg += "\nSafety violation(s) at session state " + s.id + ":\n Trace=" + trace; - } - errorMsg = appendSafetyErrorMessages(errorMsg, errors); - } - job.debugPrintln("(" + this.graph.proto + ") Checked all states: " + count); // May include unsafe states - //*/ - - if (!job.noProgress) - { - //job.debugPrintln("(" + this.graph.proto + ") Checking progress: "); // Incompatible with current errorMsg approach*/ - - Set> termsets = this.graph.getTerminalSets(); - for (Set termset : termsets) - { - /*job.debugPrintln("(" + this.graph.proto + ") Checking terminal set: " - + termset.stream().map((i) -> new Integer(all.get(i).id).toString()).collect(Collectors.joining(","))); // Incompatible with current errorMsg approach*/ - - Set starved = checkRoleProgress(states, init, termset); - Map> ignored = checkEventualReception(states, init, termset); - errorMsg = appendProgressErrorMessages(errorMsg, starved, ignored, job, states, termset); - } - } - - if (!errorMsg.equals("")) - { - //throw new ScribbleException("\n" + init.toDot() + errorMsg); - throw new ScribbleException(errorMsg); - } - //job.debugPrintln("(" + this.graph.proto + ") Progress satisfied."); // Also safety... current errorMsg approach - } - - protected String appendSafetyErrorMessages(String errorMsg, SStateErrors errors) - { - if (!errors.stuck.isEmpty()) - { - errorMsg += "\n Stuck messages: " + errors.stuck; // Deadlock from reception error - } - if (!errors.waitFor.isEmpty()) - { - errorMsg += "\n Wait-for errors: " + errors.waitFor; // Deadlock from input-blocked cycles, terminated dependencies, etc - } - if (!errors.orphans.isEmpty()) - { - errorMsg += "\n Orphan messages: " + errors.orphans; // FIXME: add sender of orphan to error message - } - if (!errors.unfinished.isEmpty()) - { - errorMsg += "\n Unfinished roles: " + errors.unfinished; - } - return errorMsg; - } - - protected String appendProgressErrorMessages(String errorMsg, Set starved, Map> ignored, - Job job, Map states, Set termset) - { - if (!starved.isEmpty()) - { - errorMsg += "\nRole progress violation for " + starved + " in session state terminal set:\n " + termSetToString(job, termset, states); - } - if (!ignored.isEmpty()) - { - errorMsg += "\nEventual reception violation for " + ignored + " in session state terminal set:\n " + termSetToString(job, termset, states); - } - return errorMsg; - } - - protected String termSetToString(Job job, Set termset, Map all) - { - return job.debug - ? termset.stream().map((i) -> all.get(i).toString()).collect(Collectors.joining(",")) - : termset.stream().map((i) -> new Integer(all.get(i).id).toString()).collect(Collectors.joining(",")); - } - - // ** Could subsume terminal state check, if terminal sets included size 1 with reflexive reachability (but not a good approach) - protected static Set checkRoleProgress(Map states, SState init, Set termset) throws ScribbleException - { - Set starved = new HashSet<>(); - Iterator i = termset.iterator(); - SState s = states.get(i.next()); - Map ss = new HashMap<>(); - s.config.efsms.keySet().forEach((r) -> ss.put(r, s)); - while (i.hasNext()) - { - SState next = states.get(i.next()); - Map tmp = next.config.efsms; - for (Role r : tmp.keySet()) - { - if (ss.get(r) != null) - { - /*if (!ss.get(r).equals(tmp.get(r))) - { - ss.put(r, null); - } - else*/ - { - for (SAction a : next.getAllActions()) - { - if (a.containsRole(r)) - { - ss.put(r, null); - break; - } - } - } - } - } - } - for (Role r : ss.keySet()) - { - SState foo = ss.get(r); - if (foo != null) - { - EFSM tmp = foo.config.efsms.get(r); - if (tmp != null) - { - if (!foo.config.canSafelyTerminate(r)) - { - if (s.config.buffs.get(r).values().stream().allMatch((v) -> v == null)) - { - starved.add(r); - } - /* - // Should be redundant given explicit reception error etc checking - else - { - safety.add(r); - }*/ - } - } - } - } - return starved; - } - - // (eventual reception) - protected static Map> checkEventualReception(Map states, SState init, Set termset) throws ScribbleException - { - Set roles = states.get(termset.iterator().next()).config.efsms.keySet(); - - Iterator i = termset.iterator(); - Map> b0 = states.get(i.next()).config.buffs.getBuffers(); - while (i.hasNext()) - { - SState s = states.get(i.next()); - SBuffers b = s.config.buffs; - for (Role r1 : roles) - { - for (Role r2 : roles) - { - ESend s0 = b0.get(r1).get(r2); - if (s0 != null) - { - ESend tmp = b.get(r1).get(r2); - if (tmp == null) - { - b0.get(r1).put(r2, null); - } - } - } - } - } - - Map> ignored = new HashMap<>(); - for (Role r1 : roles) - { - for (Role r2 : roles) - { - ESend m = b0.get(r1).get(r2); - if (m != null) - { - Set tmp = ignored.get(r2); - if (tmp == null) - { - tmp = new HashSet<>(); - ignored.put(r2, tmp); - } - tmp.add(m); - } - } - } - return ignored; - } - - @Override - public String toString() - { - return this.graph.toString(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/global/SModelFactory.java b/scribble-core/src/main/java/org/scribble/model/global/SModelFactory.java deleted file mode 100644 index 603b412ce..000000000 --- a/scribble-core/src/main/java/org/scribble/model/global/SModelFactory.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.global; - -import java.util.Map; - -import org.scribble.model.endpoint.EFSM; -import org.scribble.model.global.actions.SAccept; -import org.scribble.model.global.actions.SRequest; -import org.scribble.model.global.actions.SDisconnect; -import org.scribble.model.global.actions.SReceive; -import org.scribble.model.global.actions.SSend; -import org.scribble.model.global.actions.SWrapClient; -import org.scribble.model.global.actions.SWrapServer; -import org.scribble.type.Payload; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; - -public interface SModelFactory -{ - SGraphBuilderUtil newSGraphBuilderUtil(); // Directly created and used by Job.buildSGraph -- cf. EGraphBuilderUtil, encapsulated by EGraphBuilder AST visitor - - SSend newSSend(Role subj, Role obj, MessageId mid, Payload payload); - SReceive newSReceive(Role subj, Role obj, MessageId mid, Payload payload); - SRequest newSConnect(Role subj, Role obj, MessageId mid, Payload payload); - SAccept newSAccept(Role subj, Role obj, MessageId mid, Payload payload); - SDisconnect newSDisconnect(Role subj, Role obj); - SWrapClient newSWrapClient(Role subj, Role obj); - SWrapServer newSWrapServer(Role subj, Role obj); - - SState newSState(SConfig config); - SGraph newSGraph(GProtocolName proto, Map states, SState init); - SConfig newSConfig(Map state, SBuffers buffs); - SModel newSModel(SGraph g); -} diff --git a/scribble-core/src/main/java/org/scribble/model/global/SModelFactoryImpl.java b/scribble-core/src/main/java/org/scribble/model/global/SModelFactoryImpl.java deleted file mode 100644 index 9e9e69377..000000000 --- a/scribble-core/src/main/java/org/scribble/model/global/SModelFactoryImpl.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.global; - -import java.util.Map; - -import org.scribble.model.endpoint.EFSM; -import org.scribble.model.global.actions.SAccept; -import org.scribble.model.global.actions.SRequest; -import org.scribble.model.global.actions.SDisconnect; -import org.scribble.model.global.actions.SReceive; -import org.scribble.model.global.actions.SSend; -import org.scribble.model.global.actions.SWrapClient; -import org.scribble.model.global.actions.SWrapServer; -import org.scribble.type.Payload; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; - -// Separate E/SModelFactories fits protected E/SState constructor pattern -public class SModelFactoryImpl implements SModelFactory -{ - @Override - public SGraphBuilderUtil newSGraphBuilderUtil() - { - return new SGraphBuilderUtil(this); - } - - @Override - public SSend newSSend(Role subj, Role obj, MessageId mid, Payload payload) - { - return new SSend(subj, obj, mid, payload); - } - - @Override - public SReceive newSReceive(Role subj, Role obj, MessageId mid, Payload payload) - { - return new SReceive(subj, obj, mid, payload); - } - - @Override - public SRequest newSConnect(Role subj, Role obj, MessageId mid, Payload payload) - { - return new SRequest(subj, obj, mid, payload); - } - - @Override - public SAccept newSAccept(Role subj, Role obj, MessageId mid, Payload payload) - { - return new SAccept(subj, obj, mid, payload); - } - - @Override - public SDisconnect newSDisconnect(Role subj, Role obj) - { - return new SDisconnect(subj, obj); - } - - @Override - public SWrapClient newSWrapClient(Role subj, Role obj) - { - return new SWrapClient(subj, obj); - } - - @Override - public SWrapServer newSWrapServer(Role subj, Role obj) - { - return new SWrapServer(subj, obj); - } - - @Override - public SState newSState(SConfig config) - { - return new SState(config); - } - - @Override - public SGraph newSGraph(GProtocolName proto, Map states, SState init) - { - return new SGraph(proto, states, init); - } - - @Override - public SConfig newSConfig(Map state, SBuffers buffs) - { - return new SConfig(this, state, buffs); - } - - @Override - public SModel newSModel(SGraph g) - { - return new SModel(g); - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/global/SState.java b/scribble-core/src/main/java/org/scribble/model/global/SState.java deleted file mode 100644 index 32dd7bb2c..000000000 --- a/scribble-core/src/main/java/org/scribble/model/global/SState.java +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.global; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.scribble.model.MPrettyState; -import org.scribble.model.MState; -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EAction; -import org.scribble.model.endpoint.actions.EReceive; -import org.scribble.model.endpoint.actions.ESend; -import org.scribble.model.global.actions.SAction; -import org.scribble.type.kind.Global; -import org.scribble.type.name.Role; - -// FIXME? make a WFModel front-end class? (cf. EGraph) -// Only uses MState.id cosmetically, cf. MState equals/hash -- overrides equals/hash based on this.config (maybe extending MState is a bit misleading) -public class SState extends MPrettyState -{ - public final SConfig config; - - //protected SState(SConfig config) - protected SState(SConfig config) // FIXME: now publically mutable - { - super(Collections.emptySet()); - this.config = config; - } - - @Override - protected void addEdge(SAction a, SState s) // For access from SGraphBuilderUtil - { - super.addEdge(a, s); - } - - // 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); - } - - public SStateErrors getErrors() - { - Map stuck = this.config.getStuckMessages(); - Set> waitfor = this.config.getWaitForErrors(); - //Set> waitfor = Collections.emptySet(); - Map> orphs = this.config.getOrphanMessages(); - Map unfinished = this.config.getUnfinishedRoles(); - return new SStateErrors(stuck, waitfor, orphs, unfinished); - } - - @Override - protected String getNodeLabel() - { - String labs = this.config.toString(); - return "label=\"" + this.id + ":" + labs.substring(1, labs.length() - 1) + "\""; - } - - // FIXME? doesn't use super.hashCode (cf., equals) - @Override - public int hashCode() - { - int hash = 79; - //int hash = super.hashCode(); - 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; - } - return ((SState) o).canEquals(this) && this.config.equals(((SState) o).config); - } - - @Override - protected boolean canEquals(MState s) - { - return s instanceof SState; - } - - @Override - public String toString() - { - return this.id + ":" + this.config.toString(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/global/SStateErrors.java b/scribble-core/src/main/java/org/scribble/model/global/SStateErrors.java deleted file mode 100644 index f288c9fa9..000000000 --- a/scribble-core/src/main/java/org/scribble/model/global/SStateErrors.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.global; - -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import org.scribble.model.endpoint.EState; -import org.scribble.model.endpoint.actions.EReceive; -import org.scribble.model.endpoint.actions.ESend; -import org.scribble.type.name.Role; - -public class SStateErrors -{ - // 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 Map unfinished; // Unfinished roles - - public SStateErrors(Map receptionErrors, Set> deadlocks, Map> orphans, Map unfinished) - { - this.stuck = Collections.unmodifiableMap(receptionErrors); - this.waitFor = Collections.unmodifiableSet(deadlocks); - this.orphans = Collections.unmodifiableMap(orphans); - this.unfinished = Collections.unmodifiableMap(unfinished); - } - - 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; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/global/actions/SAccept.java b/scribble-core/src/main/java/org/scribble/model/global/actions/SAccept.java deleted file mode 100644 index fac28d9fc..000000000 --- a/scribble-core/src/main/java/org/scribble/model/global/actions/SAccept.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.global.actions; - -import org.scribble.type.Payload; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; - -public class SAccept extends SAction -{ - public SAccept(Role subj, Role obj, MessageId mid, Payload payload) - //public GAccept(Role subj, Role obj) - { - super(subj, obj, mid, payload); - //super(subj, obj, Op.EMPTY_OPERATOR, Payload.EMPTY_PAYLOAD); - } - - @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 SAccept)) - { - return false; - } - return ((SAccept) o).canEqual(this) && super.equals(o); - } - - public boolean canEqual(Object o) - { - return o instanceof SAccept; - } - - @Override - protected String getCommSymbol() - { - //return "??"; - return "<<-"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/global/actions/SAction.java b/scribble-core/src/main/java/org/scribble/model/global/actions/SAction.java deleted file mode 100644 index 10c20bc34..000000000 --- a/scribble-core/src/main/java/org/scribble/model/global/actions/SAction.java +++ /dev/null @@ -1,133 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.global.actions; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -import org.scribble.model.MAction; -import org.scribble.type.Payload; -import org.scribble.type.kind.Global; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; - -public abstract class SAction extends MAction -{ - public final Role subj; - - public SAction(Role subj, Role obj, MessageId mid, Payload payload) - { - super(obj, mid, payload); - this.subj = subj; - } - - public boolean isConnect() - { - return false; - } - - public boolean isDisconnect() - { - return false; - } - - public boolean isAccept() - { - return false; - } - - public boolean isSend() - { - return false; - } - - public boolean isReceive() - { - 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); - } - - /*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? - } - } - }*/ - - @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) // FIXME: kind - { - if (this == o) - { - return true; - } - if (!(o instanceof SAction)) - { - return false; - } - SAction a = (SAction) o; - return super.equals(o) && this.subj.equals(a.subj); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof SAction; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/global/actions/SConnect.java b/scribble-core/src/main/java/org/scribble/model/global/actions/SConnect.java deleted file mode 100644 index 594b6c782..000000000 --- a/scribble-core/src/main/java/org/scribble/model/global/actions/SConnect.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.global.actions; - -import org.scribble.type.Payload; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; - -public class SConnect extends SAction -{ - public SConnect(Role subj, Role obj, MessageId mid, Payload payload) - //public GConnect(Role subj, Role obj) - { - super(subj, obj, mid, payload); - //super(subj, obj, Op.EMPTY_OPERATOR, Payload.EMPTY_PAYLOAD); - } - - @Override - public boolean isConnect() - { - 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 SConnect)) - { - return false; - } - return ((SConnect) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof SConnect; - } - - @Override - protected String getCommSymbol() - { - //return "!!"; - return "->>"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/global/actions/SReceive.java b/scribble-core/src/main/java/org/scribble/model/global/actions/SReceive.java deleted file mode 100644 index 46915ce13..000000000 --- a/scribble-core/src/main/java/org/scribble/model/global/actions/SReceive.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.global.actions; - -import org.scribble.type.Payload; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; - -public class SReceive extends SAction -{ - public SReceive(Role subj, Role obj, MessageId mid, Payload payload) - { - super(subj, obj, mid, payload); - } - - @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 SReceive)) - { - return false; - } - return ((SReceive) o).canEqual(this) && super.equals(o); - } - - public boolean canEqual(Object o) - { - return o instanceof SReceive; - } - - @Override - protected String getCommSymbol() - { - return "?"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/global/actions/SRequest.java b/scribble-core/src/main/java/org/scribble/model/global/actions/SRequest.java deleted file mode 100644 index 93bf4b4a6..000000000 --- a/scribble-core/src/main/java/org/scribble/model/global/actions/SRequest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.global.actions; - -import org.scribble.type.Payload; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; - -public class SRequest extends SAction -{ - public SRequest(Role subj, Role obj, MessageId mid, Payload payload) - //public GConnect(Role subj, Role obj) - { - super(subj, obj, mid, payload); - //super(subj, obj, Op.EMPTY_OPERATOR, Payload.EMPTY_PAYLOAD); - } - - @Override - public boolean isConnect() - { - 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 ((SRequest) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof SRequest; - } - - @Override - protected String getCommSymbol() - { - //return "!!"; - return "->>"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/global/actions/SWrapClient.java b/scribble-core/src/main/java/org/scribble/model/global/actions/SWrapClient.java deleted file mode 100644 index 48f004961..000000000 --- a/scribble-core/src/main/java/org/scribble/model/global/actions/SWrapClient.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.global.actions; - -import org.scribble.type.Payload; -import org.scribble.type.name.Op; -import org.scribble.type.name.Role; - -public class SWrapClient extends SAction -{ - public SWrapClient(Role subj, Role obj) - { - super(subj, obj, Op.EMPTY_OPERATOR, Payload.EMPTY_PAYLOAD); - } - - @Override - public boolean isConnect() - { - 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 SWrapClient)) - { - return false; - } - return ((SWrapClient) o).canEqual(this) && super.equals(o); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof SWrapClient; - } - - @Override - protected String getCommSymbol() - { - return "(->>)"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/model/global/actions/SWrapServer.java b/scribble-core/src/main/java/org/scribble/model/global/actions/SWrapServer.java deleted file mode 100644 index 2793b0bf9..000000000 --- a/scribble-core/src/main/java/org/scribble/model/global/actions/SWrapServer.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.model.global.actions; - -import org.scribble.type.Payload; -import org.scribble.type.name.Op; -import org.scribble.type.name.Role; - -public class SWrapServer extends SAction -{ - public SWrapServer(Role subj, Role obj) - { - super(subj, obj, Op.EMPTY_OPERATOR, Payload.EMPTY_PAYLOAD); - } - - @Override - public boolean isAccept() - { - 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 SWrapServer)) - { - return false; - } - return ((SWrapServer) o).canEqual(this) && super.equals(o); - } - - public boolean canEqual(Object o) - { - return o instanceof SWrapServer; - } - - @Override - protected String getCommSymbol() - { - return "(<<-)"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/type/Message.java b/scribble-core/src/main/java/org/scribble/type/Message.java deleted file mode 100644 index b4d485772..000000000 --- a/scribble-core/src/main/java/org/scribble/type/Message.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type; - -import org.scribble.type.kind.MessageIdKind; -import org.scribble.type.kind.SigKind; -import org.scribble.type.name.MessageId; - - - -// A sig kind name: MessageSignature value (or parameter) -public interface Message extends Arg -{ - MessageId getId(); -} diff --git a/scribble-core/src/main/java/org/scribble/type/MessageSig.java b/scribble-core/src/main/java/org/scribble/type/MessageSig.java deleted file mode 100644 index 43c8fa37c..000000000 --- a/scribble-core/src/main/java/org/scribble/type/MessageSig.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type; - -import org.scribble.type.kind.OpKind; -import org.scribble.type.kind.SigKind; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Op; - -public class MessageSig implements Message -{ - public final Op op; - public final Payload payload; - - public MessageSig(Op op, Payload payload) - { - this.op = op; - this.payload = payload; - } - - @Override - public SigKind getKind() - { - return SigKind.KIND; - } - - @Override - public MessageId getId() - { - return this.op; - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof MessageSig)) - { - return false; - } - MessageSig sig = (MessageSig) 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/type/Payload.java b/scribble-core/src/main/java/org/scribble/type/Payload.java deleted file mode 100644 index b77e89f8a..000000000 --- a/scribble-core/src/main/java/org/scribble/type/Payload.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type; - -import java.util.Collections; -import java.util.List; - -import org.scribble.type.kind.Kind; -import org.scribble.type.kind.PayloadTypeKind; -import org.scribble.type.name.PayloadElemType; - -public class Payload -{ - public static final Payload EMPTY_PAYLOAD = new Payload(Collections.emptyList()); - - public final List> elems; - - public Payload(List> payload) - { - this.elems = payload; - } - - 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() - { - if (this.elems.isEmpty()) - { - return "()"; - } - String payload = "(" + this.elems.get(0); - for (PayloadElemType pt : this.elems.subList(1, this.elems.size())) - { - payload+= ", " + pt; - } - return payload + ")"; - } - - /*@Override - public boolean isParameter() - { - return false; - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/type/SessionTypeFactory.java b/scribble-core/src/main/java/org/scribble/type/SessionTypeFactory.java deleted file mode 100644 index 0cc38a63b..000000000 --- a/scribble-core/src/main/java/org/scribble/type/SessionTypeFactory.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type; - -import java.util.Arrays; - -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.ModuleName; -import org.scribble.type.name.PackageName; - -@Deprecated -public class SessionTypeFactory -{ - public SessionTypeFactory() - { - - } - - /*public static ModuleName parseModuleName(String name) - { - String[] elems = name.split("\\."); - return new ModuleName(elems); - }*/ - - // From fullname - public static GProtocolName 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); - } - GProtocolName gpn = new GProtocolName(membname); - return new GProtocolName(modname, gpn); - } - - /*public static Scope parseScope(String name) - { - String[] elems = name.split("\\."); - return new Scope(elems); - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/type/SubprotocolSig.java b/scribble-core/src/main/java/org/scribble/type/SubprotocolSig.java deleted file mode 100644 index 9d487adfd..000000000 --- a/scribble-core/src/main/java/org/scribble/type/SubprotocolSig.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type; - -import java.util.LinkedList; -import java.util.List; - -import org.scribble.type.kind.Kind; -import org.scribble.type.kind.NonRoleArgKind; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.ProtocolName; -import org.scribble.type.name.Role; - -public class SubprotocolSig -{ - public ProtocolName fmn; - //public Scope scope; - public List roles; - public List> args; - - //public SubprotocolSignature(ProtocolName fmn, Scope scope, List roles, List> args) - public SubprotocolSig(ProtocolName fmn, List roles, List> args) - { - this.fmn = fmn; - //this.scope = scope; - this.roles = new LinkedList<>(roles); - this.args = new LinkedList<>(args); - } - - @Override - public int hashCode() - { - int hash = 1093; - hash = 31 * hash + this.fmn.hashCode(); - //hash = 31 * hash + this.scope.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 == null || this.getClass() != o.getClass()) - if (!(o instanceof SubprotocolSig)) - { - return false; - } - SubprotocolSig subsig = (SubprotocolSig) o; - return this.fmn.equals(subsig.fmn) //&& this.scope.equals(subsig.scope) - && this.roles.equals(subsig.roles) && this.args.equals(subsig.args); - } - - @Override - public String toString() - { - String args = this.args.toString(); - String roles = this.roles.toString(); - return //this.scope + ":" + - this.fmn + "<" + args.substring(1, args.length() - 1) + ">(" + roles.substring(1, roles.length() - 1) + ")"; - } -} diff --git a/scribble-core/src/main/java/org/scribble/type/kind/AbstractKind.java b/scribble-core/src/main/java/org/scribble/type/kind/AbstractKind.java deleted file mode 100644 index bd839e5e3..000000000 --- a/scribble-core/src/main/java/org/scribble/type/kind/AbstractKind.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.kind; - -public abstract class AbstractKind implements Kind -{ - public AbstractKind() - { - - } - - @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.sesstype.kind.".length() + 1, s.length()); - } -} diff --git a/scribble-core/src/main/java/org/scribble/type/kind/DataTypeKind.java b/scribble-core/src/main/java/org/scribble/type/kind/DataTypeKind.java deleted file mode 100644 index 0fb05dc57..000000000 --- a/scribble-core/src/main/java/org/scribble/type/kind/DataTypeKind.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.kind; - -public class DataTypeKind extends AbstractKind implements PayloadTypeKind, ImportKind, ModuleMemberKind -{ - public static final DataTypeKind KIND = new DataTypeKind(); - - protected DataTypeKind() - { - - } - - @Override - public int hashCode() - { - return super.hashCode(); - } - - @Override - public boolean equals(Object o) - { - if (o == this) - { - return true; - } - if (!(o instanceof DataTypeKind)) - { - return false; - } - return ((DataTypeKind) o).canEqual(this); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof DataTypeKind; - } -} diff --git a/scribble-core/src/main/java/org/scribble/type/kind/MessageIdKind.java b/scribble-core/src/main/java/org/scribble/type/kind/MessageIdKind.java deleted file mode 100644 index ed3679960..000000000 --- a/scribble-core/src/main/java/org/scribble/type/kind/MessageIdKind.java +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.kind; - - -public interface MessageIdKind extends Kind -{ - -} diff --git a/scribble-core/src/main/java/org/scribble/type/kind/NonProtocolKind.java b/scribble-core/src/main/java/org/scribble/type/kind/NonProtocolKind.java deleted file mode 100644 index 7ae6e7d43..000000000 --- a/scribble-core/src/main/java/org/scribble/type/kind/NonProtocolKind.java +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.kind; - - -public interface NonProtocolKind extends Kind -{ - -} diff --git a/scribble-core/src/main/java/org/scribble/type/kind/OpKind.java b/scribble-core/src/main/java/org/scribble/type/kind/OpKind.java deleted file mode 100644 index 4a27b5566..000000000 --- a/scribble-core/src/main/java/org/scribble/type/kind/OpKind.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.kind; - -import java.io.Serializable; - -public class OpKind extends AbstractKind implements MessageIdKind, Serializable -{ - private static final long serialVersionUID = 1L; - - public static final OpKind KIND = new OpKind(); - - protected OpKind() - { - - } - - @Override - public int hashCode() - { - return super.hashCode(); - } - - @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/type/kind/PayloadTypeKind.java b/scribble-core/src/main/java/org/scribble/type/kind/PayloadTypeKind.java deleted file mode 100644 index da62c4c1a..000000000 --- a/scribble-core/src/main/java/org/scribble/type/kind/PayloadTypeKind.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.kind; - - -// Following sesstype.Arg hierarchy -public interface PayloadTypeKind extends NonRoleParamKind //ArgKind -{ - -} diff --git a/scribble-core/src/main/java/org/scribble/type/kind/ProtocolKind.java b/scribble-core/src/main/java/org/scribble/type/kind/ProtocolKind.java deleted file mode 100644 index d6d1ff137..000000000 --- a/scribble-core/src/main/java/org/scribble/type/kind/ProtocolKind.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.kind; - -public interface ProtocolKind extends ModuleMemberKind -{ - -} diff --git a/scribble-core/src/main/java/org/scribble/type/kind/ScopeKind.java b/scribble-core/src/main/java/org/scribble/type/kind/ScopeKind.java deleted file mode 100644 index 70293e71d..000000000 --- a/scribble-core/src/main/java/org/scribble/type/kind/ScopeKind.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.kind; - -public class ScopeKind extends AbstractKind -{ - public static final ScopeKind KIND = new ScopeKind(); - - protected ScopeKind() - { - - } - - @Override - public int hashCode() - { - return super.hashCode(); - } - - @Override - public boolean equals(Object o) - { - if (o == this) - { - return true; - } - if (!(o instanceof ScopeKind)) - { - return false; - } - return ((ScopeKind) o).canEqual(this); - } - - @Override - public boolean canEqual(Object o) - { - return o instanceof ScopeKind; - } -} diff --git a/scribble-core/src/main/java/org/scribble/type/name/DataType.java b/scribble-core/src/main/java/org/scribble/type/name/DataType.java deleted file mode 100644 index 7e7aa6a8f..000000000 --- a/scribble-core/src/main/java/org/scribble/type/name/DataType.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.name; - -import org.scribble.type.kind.DataTypeKind; - - -// Potentially qualified/canonical payload type name; not the AST primitive identifier -public class DataType extends MemberName implements PayloadElemType -{ - private static final long serialVersionUID = 1L; - - public DataType(ModuleName modname, DataType membname) - { - super(DataTypeKind.KIND, modname, membname); - } - - public DataType(String simplename) - { - super(DataTypeKind.KIND, simplename); - } - - public boolean isDataType() - { - return true; - } - - @Override - public DataTypeKind getKind() - { - return DataTypeKind.KIND; - } - - @Override - public DataType getSimpleName() - { - return new DataType(getLastElement()); - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof DataType)) - { - return false; - } - DataType n = (DataType) o; - return n.canEqual(this) && super.equals(o); - } - - public boolean canEqual(Object o) - { - return o instanceof DataType; - } - - @Override - public int hashCode() - { - int hash = 2767; - hash = 31 * super.hashCode(); - return hash; - } -} diff --git a/scribble-core/src/main/java/org/scribble/type/name/GDelegationType.java b/scribble-core/src/main/java/org/scribble/type/name/GDelegationType.java deleted file mode 100644 index 64a9dfd8d..000000000 --- a/scribble-core/src/main/java/org/scribble/type/name/GDelegationType.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.name; - -import java.io.IOException; -import java.io.Serializable; - -import org.scribble.type.kind.Local; - -// FIXME: factor out of name package? (and then PayloadType also needs to be moved out of name?) -public class GDelegationType implements PayloadElemType, Serializable -{ - private static final long serialVersionUID = 1L; - - private GProtocolName proto; // Cannot be final, for Serializable - private Role role; - - public GDelegationType(GProtocolName proto, Role role) - { - this.proto = proto; - this.role = role; - } - - @Override - public boolean isGDelegationType() - { - return true; - } - - public GProtocolName getGlobalProtocol() - { - return this.proto; - } - - public Role getRole() - { - return this.role; - } - - @Override - public Local getKind() - { - return Local.KIND; - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof GDelegationType)) - { - return false; - } - GDelegationType them = (GDelegationType) o; - return them.canEqual(this) && this.proto.equals(them.proto) && this.role.equals(them.role); - } - - public boolean canEqual(Object o) - { - return o instanceof GDelegationType; - } - - @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 = (GProtocolName) in.readObject(); - this.role = (Role) in.readObject(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/type/name/GProtocolName.java b/scribble-core/src/main/java/org/scribble/type/name/GProtocolName.java deleted file mode 100644 index 24172ab23..000000000 --- a/scribble-core/src/main/java/org/scribble/type/name/GProtocolName.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.name; - -import org.scribble.type.kind.Global; - - -public class GProtocolName extends ProtocolName -{ - private static final long serialVersionUID = 1L; - - public GProtocolName(ModuleName modname, ProtocolName membname) - { - super(Global.KIND, modname, membname); - } - - public GProtocolName(String simpname) - { - super(Global.KIND, simpname); - } - - @Override - public GProtocolName getSimpleName() - { - return new GProtocolName(getLastElement()); - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof GProtocolName)) - { - return false; - } - GProtocolName n = (GProtocolName) o; - return n.canEqual(this) && super.equals(o); - } - - public boolean canEqual(Object o) - { - return o instanceof GProtocolName; - } - - @Override - public int hashCode() - { - int hash = 2777; - hash = 31 * super.hashCode(); - return hash; - } -} diff --git a/scribble-core/src/main/java/org/scribble/type/name/LProtocolName.java b/scribble-core/src/main/java/org/scribble/type/name/LProtocolName.java deleted file mode 100644 index 3c0540914..000000000 --- a/scribble-core/src/main/java/org/scribble/type/name/LProtocolName.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.name; - -import org.scribble.type.kind.Local; - - -public class LProtocolName extends ProtocolName implements PayloadElemType //-- not needed, deleg elems currently have to be (Global@Role) -{ - private static final long serialVersionUID = 1L; - - public LProtocolName(ModuleName modname, ProtocolName membname) - { - super(Local.KIND, modname, membname); - } - - public LProtocolName(String simpname) - { - super(Local.KIND, simpname); - } - - /*@Override - public boolean isLDelegationType() - { - return true; - }*/ - - @Override - public LProtocolName getSimpleName() - { - return new LProtocolName(getLastElement()); - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof LProtocolName)) - { - return false; - } - LProtocolName n = (LProtocolName) o; - return n.canEqual(this) && super.equals(o); - } - - public boolean canEqual(Object o) - { - return o instanceof LProtocolName; - } - - @Override - public int hashCode() - { - int hash = 2789; - hash = 31 * super.hashCode(); - return hash; - } -} diff --git a/scribble-core/src/main/java/org/scribble/type/name/MessageId.java b/scribble-core/src/main/java/org/scribble/type/name/MessageId.java deleted file mode 100644 index 1df7a480a..000000000 --- a/scribble-core/src/main/java/org/scribble/type/name/MessageId.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.name; - -import org.scribble.type.kind.MessageIdKind; - - -public interface MessageId extends Name -{ - default boolean isOp() - { - return false; - } - - default boolean isMessageSigName() - { - return false; - } -} diff --git a/scribble-core/src/main/java/org/scribble/type/name/MessageSigName.java b/scribble-core/src/main/java/org/scribble/type/name/MessageSigName.java deleted file mode 100644 index 09a1837f0..000000000 --- a/scribble-core/src/main/java/org/scribble/type/name/MessageSigName.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.name; - -import org.scribble.type.Message; -import org.scribble.type.kind.SigKind; - - -// The name of a declared (imported) message signature member -public class MessageSigName extends MemberName implements Message, MessageId -{ - private static final long serialVersionUID = 1L; - - public MessageSigName(ModuleName modname, MessageSigName simplename) - { - super(SigKind.KIND, modname, simplename); - } - - public MessageSigName(String simplename) - { - super(SigKind.KIND, simplename); - } - - @Override - public SigKind getKind() - { - return SigKind.KIND; // Same as this.kind - } - - @Override - public MessageSigName getSimpleName() - { - return new MessageSigName(getLastElement()); - } - - @Override - public MessageId getId() - { - return this; // FIXME: should be resolved to a canonical name - } - - @Override - public boolean isMessageSigName() - { - return true; - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof MessageSigName)) - { - return false; - } - MessageSigName n = (MessageSigName) o; - return n.canEqual(this) && super.equals(o); - } - - public boolean canEqual(Object o) - { - return o instanceof MessageSigName; - } - - @Override - public int hashCode() - { - int hash = 2791; - hash = 31 * super.hashCode(); - return hash; - } -} diff --git a/scribble-core/src/main/java/org/scribble/type/name/PayloadElemType.java b/scribble-core/src/main/java/org/scribble/type/name/PayloadElemType.java deleted file mode 100644 index bdaa39d8d..000000000 --- a/scribble-core/src/main/java/org/scribble/type/name/PayloadElemType.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.name; - -import org.scribble.type.Arg; -import org.scribble.type.kind.PayloadTypeKind; - - -public interface PayloadElemType extends Arg -{ - default boolean isDataType() - { - return false; - } - - default boolean isGDelegationType() - { - return false; - } - - /*public boolean isLDelegationType() - { - return true; - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/type/name/ProtocolName.java b/scribble-core/src/main/java/org/scribble/type/name/ProtocolName.java deleted file mode 100644 index 51a6200f0..000000000 --- a/scribble-core/src/main/java/org/scribble/type/name/ProtocolName.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.name; - -import org.scribble.type.kind.ProtocolKind; - - -// Potentially qualified/canonical protocol name; not the AST primitive identifier -public abstract class ProtocolName extends MemberName -{ - private static final long serialVersionUID = 1L; - - public ProtocolName(K kind, ModuleName modname, ProtocolName membname) - { - super(kind, modname, membname); - } - - public ProtocolName(K kind, String simpname) - { - super(kind, simpname); - } - - @Override - public abstract ProtocolName getSimpleName(); -} diff --git a/scribble-core/src/main/java/org/scribble/type/name/QualifiedName.java b/scribble-core/src/main/java/org/scribble/type/name/QualifiedName.java deleted file mode 100644 index 231436556..000000000 --- a/scribble-core/src/main/java/org/scribble/type/name/QualifiedName.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.name; - -import org.scribble.type.kind.Kind; - - - -public abstract class QualifiedName extends AbstractName -{ - private static final long serialVersionUID = 1L; - - public QualifiedName(K kind, String... elems) - { - super(kind, elems); - } - - @Override - public boolean isEmpty() - { - return super.isEmpty(); - } - - @Override - public boolean isPrefixed() - { - return super.isPrefixed(); - } - - // Also done by Scope - public abstract Name getPrefix(); - public abstract Name getSimpleName(); -} diff --git a/scribble-core/src/main/java/org/scribble/type/name/Scope.java b/scribble-core/src/main/java/org/scribble/type/name/Scope.java deleted file mode 100644 index b0ed6991d..000000000 --- a/scribble-core/src/main/java/org/scribble/type/name/Scope.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package org.scribble.type.name; - -import org.scribble.type.kind.ScopeKind; - -// Should be a compound name? -public class Scope extends AbstractName -{ - private static final long serialVersionUID = 1L; - - public static final String IMPLICIT_SCOPE_PREFIX = "__scope"; - public static final Scope EMPTY_SCOPE = new Scope(); - public static final Scope ROOT_SCOPE = new Scope("__root"); - - protected Scope(String... elems) - { - super(ScopeKind.KIND, elems); - } - - public Scope(String name) - { - this(new String[] { name }); - } - - public Scope(Scope prefix, Name name) - { - this(compileScope(prefix, name)); - } - - // Also done by QualifiedName - public Scope getPrefix() - { - return new Scope(getPrefixElements()); - } - - public Scope getSimpleName() - { - return new Scope(getLastElement()); - } - - @Override - public boolean equals(Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof Scope)) - { - return false; - } - Scope n = (Scope) o; - return n.canEqual(this) && super.equals(o); - } - - public boolean canEqual(Object o) - { - return o instanceof Scope; - } - - @Override - public int hashCode() - { - int hash = 2833; - hash = 31 * super.hashCode(); - return hash; - } - - private static String[] compileScope(Scope prefix, Name name) - { - String[] tmp = prefix.getElements(); - String[] elems = new String[tmp.length + 1]; - System.arraycopy(tmp, 0, elems, 0, tmp.length); - elems[elems.length - 1] = name.toString(); - return elems; - } -} diff --git a/scribble-core/src/main/java/org/scribble/main/AntlrSourceException.java b/scribble-core/src/main/java/org/scribble/util/AntlrSourceException.java similarity index 86% rename from scribble-core/src/main/java/org/scribble/main/AntlrSourceException.java rename to scribble-core/src/main/java/org/scribble/util/AntlrSourceException.java index 12c8f3599..4ab03191b 100644 --- a/scribble-core/src/main/java/org/scribble/main/AntlrSourceException.java +++ b/scribble-core/src/main/java/org/scribble/util/AntlrSourceException.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.main; +package org.scribble.util; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -34,12 +34,13 @@ 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); + 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) - private static String getRootModuleName(CommonTree blame) // Means root of this CommonTree (not the Scribble job root, i.e. main) + 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) @@ -48,7 +49,9 @@ private static String getRootModuleName(CommonTree blame) // Means root of this } 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(".")); + return IntStream.range(0, count) + .mapToObj(i -> moddecl.getChild(i).getText()) + .collect(Collectors.joining(".")); } public AntlrSourceException(String arg0) diff --git a/scribble-core/src/main/java/org/scribble/util/ConnectedMap.java b/scribble-core/src/main/java/org/scribble/util/ConnectedMap.java index ccbfa5f4f..2273b5942 100644 --- a/scribble-core/src/main/java/org/scribble/util/ConnectedMap.java +++ b/scribble-core/src/main/java/org/scribble/util/ConnectedMap.java @@ -19,7 +19,7 @@ import java.util.Map; import java.util.Set; -import org.scribble.type.name.Role; +import org.scribble.core.type.name.Role; // FIXME: factor out with MessageIdMap // FIXME: cf, WFBuffers.connected 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 index df9aa839b..6f8e95dc6 100644 --- a/scribble-core/src/main/java/org/scribble/util/MessageIdMap.java +++ b/scribble-core/src/main/java/org/scribble/util/MessageIdMap.java @@ -19,14 +19,14 @@ import java.util.Map; import java.util.Set; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Role; +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<>(); + private Map>>> map = new HashMap<>(); public MessageIdMap() { @@ -55,7 +55,7 @@ public MessageIdMap(MessageIdMap map) } }*/ - public void putMessage(Role dest, Role src, MessageId msg) + public void putMessage(Role dest, Role src, MsgId msg) { addRolePair(dest, src); this.map.get(dest).get(src).add(msg); @@ -75,7 +75,7 @@ public void putMessage(Role dest, Role src, MessageId msg) } }*/ - public void putMessages(Role dest, Role src, Set> msgs) + public void putMessages(Role dest, Role src, Set> msgs) { addRolePair(dest, src); this.map.get(dest).get(src).addAll(msgs); @@ -108,14 +108,14 @@ public Set getSources(Role dest) return srcs; }*/ - public Set> getMessages(Role dest, Role src) + public Set> getMessages(Role dest, Role src) { return this.map.get(dest).get(src); } - public Set> getMessages(Role dest) + public Set> getMessages(Role dest) { - Set> tmp = new HashSet<>(); + Set> tmp = new HashSet<>(); getSources(dest).forEach((src) -> tmp.addAll(getMessages(dest, src))); return tmp; } @@ -139,7 +139,7 @@ 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, new HashSet<>()); } diff --git a/scribble-core/src/main/java/org/scribble/util/Pair.java b/scribble-core/src/main/java/org/scribble/util/Pair.java index f6a3f2fc8..249590cb1 100644 --- a/scribble-core/src/main/java/org/scribble/util/Pair.java +++ b/scribble-core/src/main/java/org/scribble/util/Pair.java @@ -44,8 +44,7 @@ public boolean equals(Object o) { return false; } - @SuppressWarnings("rawtypes") - Pair p = (Pair) o; // Could store T1.class and T2.class as fields, but probably better to do "structurally" as here - return this.left.equals(p.left) && this.right.equals(p.right); + 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 index 8fe952614..662d23f5d 100644 --- a/scribble-core/src/main/java/org/scribble/util/ScribParserException.java +++ b/scribble-core/src/main/java/org/scribble/util/ScribParserException.java @@ -13,7 +13,7 @@ */ package org.scribble.util; -// FIXME: should be in parser module -- maybe make a ModuleLoadingException wrapper? +// CHECKME: should be in parser module? -- maybe make a ModuleLoadingException wrapper? public class ScribParserException extends Exception { /** diff --git a/scribble-core/src/main/java/org/scribble/util/ScribUtil.java b/scribble-core/src/main/java/org/scribble/util/ScribUtil.java index ba0ed752b..94002fd7f 100644 --- a/scribble-core/src/main/java/org/scribble/util/ScribUtil.java +++ b/scribble-core/src/main/java/org/scribble/util/ScribUtil.java @@ -19,48 +19,10 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.util.List; import java.util.concurrent.Callable; -import java.util.stream.Collectors; - -import org.scribble.ast.AstFactory; -import org.scribble.ast.ScribNode; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleException; public class ScribUtil { - // 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))).collect(Collectors.toList()); - } - public static T handleLambdaScribbleException(Callable c) { try @@ -69,22 +31,26 @@ public static T handleLambdaScribbleException(Callable c) } catch (Exception se) { - throw new RuntimeScribbleException(se); // Maybe this hack is not worth it? Better to throw directly as ScribbleException from a regular foreach + 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 ScribbleException + public static String[] runProcess(String... cmdAndArgs) + throws ScribException { - try - { + try + { ProcessBuilder pb = new ProcessBuilder(cmdAndArgs); Process p = pb.start(); p.waitFor(); InputStream is = p.getInputStream(), eis = p.getErrorStream(); - InputStreamReader isr = new InputStreamReader(is), eisr = new InputStreamReader(eis); - BufferedReader br = new BufferedReader(isr), ebr = new BufferedReader(eisr); + 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) { @@ -98,12 +64,13 @@ public static String[] runProcess(String... cmdAndArgs) throws ScribbleException } catch (IOException | InterruptedException e) { - throw new ScribbleException(e); + throw new ScribException(e); } } // Warning: doesn't check if file exists - public static void writeToFile(String path, String text) throws ScribbleException + public static void writeToFile(String path, String text) + throws ScribException { File file = new File(path); File parent = file.getParentFile(); @@ -118,7 +85,7 @@ public static void writeToFile(String path, String text) throws ScribbleExceptio } catch (IOException e) { - throw new ScribbleException(e); + throw new ScribException(e); } } } diff --git a/scribble-core/src/main/java/org/scribble/visit/AstVisitor.java b/scribble-core/src/main/java/org/scribble/visit/AstVisitor.java deleted file mode 100644 index 6815676d3..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/AstVisitor.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.main.Job; -import org.scribble.main.ScribbleException; - -// 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) -public abstract class AstVisitor -{ - public final Job job; // Immutable except for JobContext internals - - //private ModuleContext mcontext; // Factor up to ModelVisitor? (will be null before context building) -- maybe make a ModuleVisitor - - protected AstVisitor(Job job) - { - this.job = job; - } - - public ScribNode visit(ScribNode parent, ScribNode child) throws ScribbleException - { - enter(parent, child); - ScribNode visited = child.visitChildren(this); // visited means "children visited so far"; we're about to visit "this" now via "leave" - return leave(parent, child, visited); - } - - protected void enter(ScribNode parent, ScribNode child) throws ScribbleException - { - - } - - protected ScribNode leave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - return visited; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/EnvVisitor.java b/scribble-core/src/main/java/org/scribble/visit/EnvVisitor.java deleted file mode 100644 index 02741973b..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/EnvVisitor.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.LinkedList; - -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ScribNode; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.visit.context.ModuleContextVisitor; -import org.scribble.visit.env.Env; - -// By default, EnvVisitor only manipulates internal Env stack -- so AST/dels not affected -// Attaching Envs to Dels has to be done manually by each pass -// FIXME: make a ProtocolDeclContextVisitor (caches ProtocolDeclContext, e.g. roles, modifiers) between this and ModuleContextVisitor -public abstract class EnvVisitor> extends ModuleContextVisitor -{ - private LinkedList envs = new LinkedList(); // Deque - - public EnvVisitor(Job job) - { - super(job); - } - - @Override - protected final void enter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.enter(parent, child); - if (child instanceof ProtocolDecl) // Only the root ProtocolDecl is visited: subprotocols visit the body directly - { - ProtocolDecl pd = (ProtocolDecl) child; - pushEnv(makeRootProtocolDeclEnv(pd)); - } - envEnter(parent, child); - } - - @Override - protected final ScribNode leave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - ScribNode n = envLeave(parent, child, visited); - if (n instanceof ProtocolDecl) // Only the root ProtocolDecl is visited by SubprotocolVisitor (subprotocols visit the body directly) - { - this.envs.pop(); - } - return super.leave(parent, child, n); - } - - protected abstract T makeRootProtocolDeclEnv(ProtocolDecl pd); - - protected void envEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - //..could push copy of parent Env onto visitor stack for use by visitor pass (del env-leave routine should pop and push back the final result) - //..but only if want an env for every node (unless restrict to specific nodes types -- e.g. interaction nodes) -- as opposed to only e.g. compound nodes, as done via del - //..so either do base env management here or via del -- here, need to do instanceof; in delegates, need to duplicate base push/pop for each pass - //..no: should be only compound interaction nodes, as typing environments - //return this; - } - - protected ScribNode envLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - return visited; - } - - // Hack? e.g. for ModuleDecl - public boolean hasEnv() - { - return !this.envs.isEmpty(); - } - - public T peekEnv() - { - return this.envs.peek(); - } - - public T peekParentEnv() - { - //return this.envs.get(this.envs.size() - 2); - return this.envs.get(1); - } - - public void pushEnv(T env) - { - this.envs.push(env); - } - - public T popEnv() - { - return this.envs.pop(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/InlinedProtocolUnfolder.java b/scribble-core/src/main/java/org/scribble/visit/InlinedProtocolUnfolder.java deleted file mode 100644 index 5aaa86dc4..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/InlinedProtocolUnfolder.java +++ /dev/null @@ -1,163 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.AstFactory; -import org.scribble.ast.InteractionSeq; -import org.scribble.ast.ProtocolBlock; -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.Recursion; -import org.scribble.ast.ScribNode; -import org.scribble.ast.global.GProtocolBlock; -import org.scribble.ast.global.GRecursion; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.ast.local.LRecursion; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.del.ProtocolDefDel; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.Global; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.RecVar; -import org.scribble.visit.env.UnfoldingEnv; - -// Statically unfolds unguarded recursions and continues "directly under" choices -// N.B. cf. UnfoldingVisitor "lazily" unfolds every rec once on demand -public class InlinedProtocolUnfolder extends InlinedProtocolVisitor -{ - public static final String DUMMY_REC_LABEL = "__"; - - // NOTE: assumes unique recvars up to this point, i.e. no recvar shadowing (treated internally by protocoldef-inlining) -- unfolding of unguardeds will, however, result in "unfolding shadowing" - protected Map> recs = new HashMap<>(); // Could parameterise recvars to be global/local - private Set recsToUnfold = new HashSet<>(); - - public InlinedProtocolUnfolder(Job job) - { - super(job); - } - - public boolean shouldUnfoldForUnguardedRec(RecVar rv) - { - return this.recsToUnfold.contains(rv); - } - - // Unguarded continues directly under choices need to be unfolded to make current graph building work (continue side effects GraphBuilder state to re-set entry to rec state -- which makes output dependent on choice block order, and can attach subsequent choice paths onto the rec state instead of the original choice state) - // Maybe fix this problem inside graph building rather than unfolding here (this unfolding is conservative -- not always needed for every unguarded continue) -- depends if it helps any other inlined passes? - public boolean isContinueUnguarded(RecVar rv) - { - return peekEnv().shouldUnfold(); - } - - @Override - protected UnfoldingEnv makeRootProtocolDeclEnv(ProtocolDecl pd) - { - return new UnfoldingEnv(); - } - - @Override - public ScribNode visit(ScribNode parent, ScribNode child) throws ScribbleException - { - if (child instanceof Recursion) - { - if (peekEnv().shouldUnfold()) - { - enter(parent, child); - ScribNode visited = unfold((Recursion) child); - return leave(parent, child, visited); - } - else - { - return super.visit(parent, child); - } - } - else - { - ScribNode visited = super.visit(parent, child); - if (visited instanceof ProtocolDecl) - { - ProtocolDecl pd = (ProtocolDecl) visited; - this.job.debugPrintln("\n[DEBUG] Unfolded inlined protocol " - + pd.getFullMemberName(this.job.getContext().getModule(getModuleContext().root)) + ":\n" - + ((ProtocolDefDel) pd.def.del()).getInlinedProtocolDef()); - } - return visited; - } - } - - // Not doing the actual unfolding here: replace the rec with a dummy (i.e. alpha the original rec to another unused lab) and will do any actual unfolding inside the recursive child accept (upon Continue) - private ScribNode unfold(Recursion rec) throws ScribbleException - { - RecVar rv = rec.recvar.toName(); - ProtocolBlock pb = rec.block; - // Clone unnecessary: can visit the original block, apart from any continues to substitute (done in InteractionSeqDel) - this.recsToUnfold.add(rv); - /*RecVarNode dummy = (RecVarNode) AstFactoryImpl.FACTORY.SimpleNameNode(RecVarKind.KIND, DUMMY_REC_LABEL); - //RecVarNode dummy = rec.recvar.clone(); - ScribNode n = rec.reconstruct(dummy, ScribUtil.checkNodeClassEquality(pb, pb.accept(this))); // Returning a rec because it needs to go into the InteractionSeq - // reconstruct makes sense here, actually reconstructing this rec with new label but same block (and keep the same del etc)*/ - InteractionSeq seq = pb.getInteractionSeq(); - ScribNode n = seq.accept(this); - this.recsToUnfold.remove(rv); - return n; - } - - @Override - protected void inlinedEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.inlinedEnter(parent, child); - child.del().enterInlinedProtocolUnfolding(parent, child, this); - } - - @Override - protected ScribNode inlinedLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveInlinedProtocolUnfolding(parent, child, this, visited); - return super.inlinedLeave(parent, child, visited); - } - - public Recursion getRecVar(RecVar recvar) - { - return this.recs.get(recvar); - } - - // Maybe possible to revise this algorithm to handle shadowed recs, but currently requires unique recvar names - public void setRecVar(AstFactory af, RecVar recvar, Recursion rec) throws ScribbleException - { - ProtocolBlock block = (ProtocolBlock) rec.getBlock().accept(this); - RecVarNode rv = rec.recvar.clone(af); - Recursion unfolded; - if (rec.getKind() == Global.KIND) - { - unfolded = ((GRecursion) rec).reconstruct(rv, (GProtocolBlock) block); - } - else - { - unfolded = ((LRecursion) rec).reconstruct(rv, (LProtocolBlock) block); - /*LRecursion clone = (LRecursion) rec.clone(af); // Try to be more compatible with extensions that have different reconstructs // FIXME: reconstruct should be "protected"? - clone.block = (LProtocolBlock) block; // No: cannot set new block - unfolded = (LRecursion) clone.del(rec.del());*/ - } - this.recs.put(recvar, unfolded); - } - - public void removeRecVar(RecVar recvar) - { - this.recs.remove(recvar); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/InlinedProtocolVisitor.java b/scribble-core/src/main/java/org/scribble/visit/InlinedProtocolVisitor.java deleted file mode 100644 index 5dec34618..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/InlinedProtocolVisitor.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ProtocolDef; -import org.scribble.ast.ScribNode; -import org.scribble.del.ProtocolDefDel; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.visit.env.Env; - -public abstract class InlinedProtocolVisitor> extends EnvVisitor -{ - public InlinedProtocolVisitor(Job job) - { - super(job); - } - - @Override - public ScribNode visit(ScribNode parent, ScribNode child) throws ScribbleException - { - enter(parent, child); - ScribNode visited = visitInlinedProtocol(parent, child); - return leave(parent, child, visited); - } - - protected ScribNode visitInlinedProtocol(ScribNode parent, ScribNode child) throws ScribbleException - { - if (child instanceof ProtocolDef) - { - return visitOverrideForProtocolDef(parent, (ProtocolDef) child); // parent is InteractionSequence - } - else - { - return child.visitChildren(this); - // The base (super) behaviour (could factor it out in ModelVisitor as its own visitor method) -- not super.visit because that does enter/exit - } - } - - // N.B. results of visiting inlined version are stored back to inlined field, but original AST is unaffected -- so any Env/Del or AST updates to inlined version do not reflect back onto original AST -- a motivation for the original SubprotocolVisitor approach - private ScribNode visitOverrideForProtocolDef(ScribNode parent, ProtocolDef pd) throws ScribbleException - { - ProtocolDef inlined = ((ProtocolDefDel) pd.del()).getInlinedProtocolDef(); - if (inlined == null) - { - throw new ScribbleException("InlineProtocolVisitor error: " + pd); // E.g. -fsm when inconsistent choice subjects - // FIXME: shouldn't occur any more? - } - - /*if (this instanceof EndpointGraphBuilder) - { - System.out.println("\nBuilding graph from: " + inlined + "\n"); - }*/ - - ProtocolDef visited = (ProtocolDef) inlined.visitChildren(this); - ProtocolDefDel del = (ProtocolDefDel) pd.del(); - return pd.del(del.setInlinedProtocolDef(visited)); - } - - @Override - protected final void envEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.envEnter(parent, child); - inlinedEnter(parent, child); - } - - @Override - protected final ScribNode envLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - ScribNode n = inlinedLeave(parent, child, visited); - return super.envLeave(parent, child, n); - } - - protected void inlinedEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - - } - - protected ScribNode inlinedLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - return visited; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/NoEnvInlinedProtocolVisitor.java b/scribble-core/src/main/java/org/scribble/visit/NoEnvInlinedProtocolVisitor.java deleted file mode 100644 index dd308b876..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/NoEnvInlinedProtocolVisitor.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ProtocolDecl; -import org.scribble.main.Job; -import org.scribble.visit.env.DummyEnv; - -public abstract class NoEnvInlinedProtocolVisitor extends InlinedProtocolVisitor -{ - public NoEnvInlinedProtocolVisitor(Job job) - { - super(job); - } - - @Override - protected final DummyEnv makeRootProtocolDeclEnv(ProtocolDecl pd) - { - return DummyEnv.DUMMY; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/NoEnvOffsetSubprotocolVisitor.java b/scribble-core/src/main/java/org/scribble/visit/NoEnvOffsetSubprotocolVisitor.java deleted file mode 100644 index 81df0f60f..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/NoEnvOffsetSubprotocolVisitor.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ProtocolDecl; -import org.scribble.main.Job; -import org.scribble.visit.env.DummyEnv; - -public abstract class NoEnvOffsetSubprotocolVisitor extends OffsetSubprotocolVisitor -{ - public NoEnvOffsetSubprotocolVisitor(Job job) - { - super(job); - } - - @Override - protected final DummyEnv makeRootProtocolDeclEnv(ProtocolDecl pd) - { - return DummyEnv.DUMMY; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/NoEnvSubprotocolVisitor.java b/scribble-core/src/main/java/org/scribble/visit/NoEnvSubprotocolVisitor.java deleted file mode 100644 index d28b58294..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/NoEnvSubprotocolVisitor.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ProtocolDecl; -import org.scribble.main.Job; -import org.scribble.visit.env.DummyEnv; - -public abstract class NoEnvSubprotocolVisitor extends SubprotocolVisitor -{ - public NoEnvSubprotocolVisitor(Job job) - { - super(job); - } - - @Override - protected final DummyEnv makeRootProtocolDeclEnv(ProtocolDecl pd) - { - return DummyEnv.DUMMY; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/NoEnvUnfoldingVisitor.java b/scribble-core/src/main/java/org/scribble/visit/NoEnvUnfoldingVisitor.java deleted file mode 100644 index c390ac994..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/NoEnvUnfoldingVisitor.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.ProtocolDecl; -import org.scribble.main.Job; -import org.scribble.visit.env.DummyEnv; - -public abstract class NoEnvUnfoldingVisitor extends UnfoldingVisitor -{ - public NoEnvUnfoldingVisitor(Job job) - { - super(job); - } - - @Override - protected final DummyEnv makeRootProtocolDeclEnv(ProtocolDecl pd) - { - return DummyEnv.DUMMY; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/OffsetSubprotocolVisitor.java b/scribble-core/src/main/java/org/scribble/visit/OffsetSubprotocolVisitor.java deleted file mode 100644 index 9525e8c88..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/OffsetSubprotocolVisitor.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Map; - -import org.scribble.ast.NonRoleArgNode; -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ScribNode; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.Arg; -import org.scribble.type.kind.NonRoleArgKind; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.Role; -import org.scribble.visit.env.Env; - -// Can probably be fully replaced by SubprotocolVisitor -// Projector, ReachabilityChecker, etc don't need to be offset visitors -public abstract class OffsetSubprotocolVisitor> extends SubprotocolVisitor -{ - public OffsetSubprotocolVisitor(Job job) - { - super(job); - } - - // Doesn't push a subprotocol signature (i.e. on root entry); only records the roles/args -- why? because sigs are based on vals (from the first do), not the root proto params? -- but it would be fine to use the params? - @Override - protected void enterRootProtocolDecl(ProtocolDecl pd) - { - Map rolemap = makeRootRoleSubsMap(pd.header.roledecls); - Map, NonRoleArgNode> argmap = makeRootNonRoleSubsMap(pd.header.paramdecls); - this.rolemaps.push(rolemap); - this.argmaps.push(argmap); - } - - @Override - protected final ScribNode visitForSubprotocols(ScribNode parent, ScribNode child) throws ScribbleException - { - return visitForOffsetSubprotocols(parent, child); - } - - protected ScribNode visitForOffsetSubprotocols(ScribNode parent, ScribNode child) throws ScribbleException - { - return super.visitForSubprotocols(parent, child); - } - - @Override - protected final void envLeaveProtocolDeclOverride(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - this.rolemaps.pop(); - this.argmaps.pop(); - } - - @Override - protected final void subprotocolEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.subprotocolEnter(parent, child); - offsetSubprotocolEnter(parent, child); - } - - @Override - protected final ScribNode subprotocolLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - ScribNode n = offsetSubprotocolLeave(parent, child, visited); - return super.subprotocolLeave(parent, child, n); - } - - protected void offsetSubprotocolEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - - } - - protected ScribNode offsetSubprotocolLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - return visited; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/ProtocolDefInliner.java b/scribble-core/src/main/java/org/scribble/visit/ProtocolDefInliner.java deleted file mode 100644 index 6c4679b84..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/ProtocolDefInliner.java +++ /dev/null @@ -1,182 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Map; - -import org.scribble.ast.Do; -import org.scribble.ast.InteractionSeq; -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ModuleContext; -import org.scribble.ast.global.GDo; -import org.scribble.ast.local.LDo; -import org.scribble.del.ProtocolDefDel; -import org.scribble.del.global.GDoDel; -import org.scribble.del.local.LDoDel; -import org.scribble.main.Job; -import org.scribble.main.JobContext; -import org.scribble.main.ScribbleException; -import org.scribble.type.SubprotocolSig; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.RecVar; -import org.scribble.visit.env.InlineProtocolEnv; - -public class ProtocolDefInliner extends SubprotocolVisitor -{ - private Map subprotoRecVars = new HashMap<>(); // RecVars translation for subprotocol inlining - - private Map recvars = new HashMap<>(); // Original RecVars, nesting count - - public ProtocolDefInliner(Job job) - { - super(job); - } - - public RecVar getSubprotocolRecVar(SubprotocolSig subsig) - { - return this.subprotoRecVars.get(subsig); - } - - public void setSubprotocolRecVar(SubprotocolSig subsig) - { - this.subprotoRecVars.put(subsig, new RecVar(newSubprotocoolRecVarId(subsig))); - } - - public void removeSubprotocolRecVar(SubprotocolSig subsig) - { - this.subprotoRecVars.remove(subsig); - } - - private String newSubprotocoolRecVarId(SubprotocolSig sig) - { - // Hacky - return sig.toString() - .replace('.', '_') - .replace('<', '_') - .replace('>', '_') - .replace('(', '_') - .replace(')', '_') - .replace(' ', '_') - .replace(',', '_'); - } - - @Override - protected InlineProtocolEnv makeRootProtocolDeclEnv(ProtocolDecl pd) - { - return new InlineProtocolEnv(); - } - - @Override - public ScribNode visit(ScribNode parent, ScribNode child) throws ScribbleException - { - enter(parent, child); - ScribNode visited = visitForSubprotocols(parent, child); - if (visited instanceof ProtocolDecl) - { - ProtocolDecl pd = (ProtocolDecl) visited; - this.job.debugPrintln("\n[DEBUG] Inlined root protocol " - + pd.getFullMemberName(this.job.getContext().getModule(getModuleContext().root)) + ":\n" - + ((ProtocolDefDel) pd.def.del()).getInlinedProtocolDef()); - } - return leave(parent, child, visited); - } - - @Override - public ScribNode visitForSubprotocols(ScribNode parent, ScribNode child) throws ScribbleException - { - if (child instanceof Do) - { - return visitOverrideForDo((InteractionSeq) parent, (Do) child); - } - ScribNode visited = super.visitForSubprotocols(parent, child); - /*if (visited instanceof ProtocolDecl) - { - ProtocolDecl pd = (ProtocolDecl) visited; - getJob().debugPrintln("\n[DEBUG] Inlined protocol " - + pd.getFullMemberName(getJobContext().getModule(getModuleContext().root)) + ":\n" - + ((ProtocolDefDel) pd.def.del()).getInlinedProtocolDef()); - }*/ - return visited; - } - - protected Do visitOverrideForDo(InteractionSeq parent, Do child) throws ScribbleException - { - if (!isCycle()) - { - //return (GDo) super.visitForSubprotocols(parent, child); - // Duplicated from SubprotocolVisitor#visitOverrideFoDo and modified to access discarded env -- FIXME: factor out this facility better - JobContext jc = this.job.getContext(); - ModuleContext mc = getModuleContext(); - ProtocolDecl pd = child.getTargetProtocolDecl(jc, mc); - ScribNode seq = applySubstitutions(pd.def.block.seq.clone(this.job.af)); - seq = seq.accept(this); - pushEnv(popEnv().setTranslation(((InlineProtocolEnv) seq.del().env()).getTranslation())); - return child; - } - - // If cycle, super routine does nothing anyway, so we can just replace with new stuff here - return (child instanceof GDo) - ? ((GDoDel) child.del()).visitForSubprotocolInlining(this, (GDo) child) - : ((LDoDel) child.del()).visitForSubprotocolInlining(this, (LDo) child); - } - - @Override - protected void subprotocolEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.subprotocolEnter(parent, child); - child.del().enterProtocolInlining(parent, child, this); - } - - @Override - protected ScribNode subprotocolLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveProtocolInlining(parent, child, this, visited); - return super.subprotocolLeave(parent, child, visited); - } - - public void pushRecVar(RecVar rv) - { - if (!this.recvars.containsKey(rv)) - { - this.recvars.put(rv, 0); - } - else - { - this.recvars.put(rv, this.recvars.get(rv) + 1); - } - } - - public void popRecVar(RecVar rv) - { - Integer i = this.recvars.get(rv); - if (i == 0) - { - this.recvars.remove(rv); - } - else - { - this.recvars.put(rv, i - 1); - } - } - - // Refactored here from NameDisambiguation - public String getCanonicalRecVarName(RecVar rv) - { - //return getCanonicalRecVarName(this.getModuleContext().root, this.root.header.getDeclName(), rv.toString() + "_" + this.recvars.get(rv)); - Integer i = this.recvars.get(rv); - return (i == 0) ? rv.toString() : (rv.toString() + i); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/SubprotocolVisitor.java b/scribble-core/src/main/java/org/scribble/visit/SubprotocolVisitor.java deleted file mode 100644 index ba3ea0491..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/SubprotocolVisitor.java +++ /dev/null @@ -1,338 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Stack; -import java.util.stream.Collectors; - -import org.scribble.ast.Do; -import org.scribble.ast.NonRoleArgList; -import org.scribble.ast.NonRoleArgNode; -import org.scribble.ast.NonRoleParamDecl; -import org.scribble.ast.NonRoleParamDeclList; -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.RoleArgList; -import org.scribble.ast.RoleDeclList; -import org.scribble.ast.ScopedNode; -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ModuleContext; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.main.Job; -import org.scribble.main.JobContext; -import org.scribble.main.ScribbleException; -import org.scribble.type.Arg; -import org.scribble.type.SubprotocolSig; -import org.scribble.type.kind.NonRoleArgKind; -import org.scribble.type.kind.NonRoleParamKind; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.Name; -import org.scribble.type.name.ProtocolName; -import org.scribble.type.name.Role; -import org.scribble.type.name.Scope; -import org.scribble.visit.env.Env; - -public abstract class SubprotocolVisitor> extends EnvVisitor -{ - protected List stack = new LinkedList<>(); - - // name in the current protocoldecl scope -> the original name node in the root protocol decl - protected Stack> rolemaps = new Stack<>(); - protected Stack, NonRoleArgNode>> argmaps = new Stack<>(); - - private Scope scope = null; - - public SubprotocolVisitor(Job job) - { - super(job); - } - - // Pushes a subprotocol signature (i.e. on root entry) - protected void enterRootProtocolDecl(ProtocolDecl pd) - { - Map rolemap = makeRootRoleSubsMap(pd.header.roledecls); - Map, NonRoleArgNode> argmap = makeRootNonRoleSubsMap(pd.header.paramdecls); - this.rolemaps.push(rolemap); - this.argmaps.push(argmap); - - ModuleContext mcontext = getModuleContext(); - ProtocolName fullname = mcontext.getVisibleProtocolDeclFullName(pd.header.getDeclName()); - List roleargs = pd.header.roledecls.getRoles(); - List> nonroleargs = - pd.header.paramdecls.getDecls().stream().map((param) -> paramDeclToArg(param)).collect(Collectors.toList()); - pushSubprotocolSig(fullname, roleargs, nonroleargs); - } - - // 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 parent, ScribNode child) throws ScribbleException - { - enter(parent, child); - ScribNode visited = visitForSubprotocols(parent, child); - return leave(parent, child, visited); - } - - // Subclasses can override this to disable subprotocol visiting - protected ScribNode visitForSubprotocols(ScribNode parent, ScribNode child) throws ScribbleException - { - if (child instanceof Do) - { - return visitOverrideForDo(parent, (Do) child); // parent is InteractionSequence - } - else - { - return child.visitChildren(this); - // The base (super) behaviour (could factor it out in ModelVisitor as its own visitor method) - } - } - - // The Do node itself is no longer visited -- FIXME: projection needs to visit it -- no: that's in enter/leave, visited means "visit children" - protected Do visitOverrideForDo(ScribNode parent, Do doo) throws ScribbleException - { - if (!isCycle()) - { - JobContext jc = this.job.getContext(); - ModuleContext mc = getModuleContext(); - ProtocolDecl pd = doo.getTargetProtocolDecl(jc, mc); - // Target is cloned: fresh dels and envs, which will be discarded - ScribNode seq = applySubstitutions(pd.def.block.seq.clone(this.job.af)); // Visit the seq? -- or visit the interactions in the seq directly? - // Visit seq/interactions under current environment - seq.accept(this); // Result from visiting subprotocol body is discarded - } - return doo; - } - - protected boolean overrideSubstitution() - { - return false; - } - - protected ScribNode applySubstitutions(ScribNode n) - { - if (overrideSubstitution()) - { - return n; - } - try - { - return n.accept(new Substitutor(this.job, this.rolemaps.peek(), this.argmaps.peek())); - } - catch (ScribbleException e) - { - throw new RuntimeException("Shouldn't get in here: " + n); - } - } - - @Override - protected final void envEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.envEnter(parent, child); - - if (child instanceof ProtocolDecl) - { - setScope(Scope.ROOT_SCOPE); - enterRootProtocolDecl((ProtocolDecl) child); - } - if (child instanceof ScopedNode) - { - ScopedNode sn = (ScopedNode) child; - if(!sn.isEmptyScope()) - { - setScope(new Scope(getScope(), sn.getScopeElement())); - } - } - if (child instanceof Do) - { - enterSubprotocol((Do) child); // Scope already pushed - } - subprotocolEnter(parent, child); - } - - @Override - protected final ScribNode envLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - ScribNode n = subprotocolLeave(parent, child, visited); - if (child instanceof ProtocolDecl) - { - envLeaveProtocolDeclOverride(parent, child, visited); - } - if (child instanceof Do) // child or visited/n? - { - leaveSubprotocol(); - } - if (child instanceof ScopedNode && !((ScopedNode) child).isEmptyScope()) - { - setScope(getScope().getPrefix()); - } - return super.envLeave(parent, child, n); - } - - // Hack for OffsetSubprotocolVisitor - protected void envLeaveProtocolDeclOverride(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - leaveSubprotocol(); - } - - protected void subprotocolEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - - } - - protected ScribNode subprotocolLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - return visited; - } - - private void enterSubprotocol(Do doo) - { - ProtocolName fullname = getModuleContext().checkProtocolDeclDependencyFullName(doo.proto.toName()); - // namedisamb should already have converted proto to the fullname -- in order for inlining to work - pushSubprotocolSig(fullname, doo.roles.getRoles(), doo.args.getArguments()); - pushNameMaps(fullname, doo); - } - - // Also used for leaving root protocoldecl, for convenience - private void leaveSubprotocol() - { - this.stack.remove(this.stack.size() - 1); - this.rolemaps.pop(); - this.argmaps.pop(); - } - - private void pushSubprotocolSig(ProtocolName fullname, List roleargs, List> nonroleargs) - { - SubprotocolSig subsig = new SubprotocolSig(fullname, roleargs, nonroleargs); - this.stack.add(subsig); - } - - private void pushNameMaps(ProtocolName fullname, Do doo) - { - ProtocolDecl pd = this.job.getContext().getModule(fullname.getPrefix()).getProtocolDecl(fullname.getSimpleName()); - this.rolemaps.push(makeRoleSubsMap(this.rolemaps.get(0), doo.roles, pd.header.roledecls)); - this.argmaps.push(makeNonRoleSubsMap(this.argmaps.get(0), doo.args, pd.header.paramdecls)); - } - - public boolean isRootedCycle() - { - return this.stack.size() > 1 && this.stack.get(0).equals(this.stack.get(this.stack.size() - 1)); - } - - public boolean isCycle() - { - return getCycleEntryIndex() != -1; - } - - public int getCycleEntryIndex() - { - int size = this.stack.size(); - if (size > 1) - { - SubprotocolSig last = this.stack.get(size - 1); - for (int i = size - 2; i >= 0; i--) - { - if (this.stack.get(i).equals(last)) // FIXME: doesn't support recursive scoped subprotocols, i.e. cycle detection not general enough? - { - return i; - } - } - } - return -1; - } - - public List getStack() - { - return this.stack; - } - - public boolean isStackEmpty() - { - return this.stack.isEmpty(); - } - - public SubprotocolSig peekStack() - { - return this.stack.get(this.stack.size() - 1); - } - - public Scope getScope() - { - return this.scope; - } - - protected void setScope(Scope scope) - { - this.scope = scope; - } - - protected static Map makeRootRoleSubsMap(RoleDeclList rdl) - { - return rdl.getDecls().stream() - .collect(Collectors.toMap((r) -> r.getDeclName(), (r) -> (RoleNode) r.name)); - } - - protected static Map, NonRoleArgNode> makeRootNonRoleSubsMap(NonRoleParamDeclList pdl) - { - return pdl.getDecls().stream() - .collect(Collectors.toMap((p) -> (Arg) p.getDeclName(), (p) -> (NonRoleArgNode) p.name)); - } - - protected static Map makeRoleSubsMap(Map root, RoleArgList ral, RoleDeclList rdl) - { - Iterator roleargs = ral.getRoles().iterator(); - return rdl.getRoles().stream().collect(Collectors.toMap((r) -> r, (r) -> root.get(roleargs.next()))); - } - - protected static Map, NonRoleArgNode> - makeNonRoleSubsMap(Map, NonRoleArgNode> root, NonRoleArgList nral, NonRoleParamDeclList nrpdl) - { - Map, NonRoleArgNode> newmap = new HashMap<>(); - - // Using arg and argnode views of the arglist - Iterator> nonroleargs = nral.getArguments().iterator(); - Iterator nonroleargnodes = nral.getArgumentNodes().iterator(); - for (Name param : nrpdl.getParameters()) - { - Arg arg = nonroleargs.next(); - NonRoleArgNode argnode; - if (root.containsKey(arg)) // A root param propagated through to here as an arg: get the root argnode - { - argnode = root.get(arg); - nonroleargnodes.next(); - } - else - { - argnode = nonroleargnodes.next(); // The argnode correspoding to the current arg - } - newmap.put((Arg) param, argnode); - } - - return newmap; - } - - private static Arg paramDeclToArg(NonRoleParamDecl pd) - { - Name n = pd.getDeclName(); - if (!(n instanceof Arg)) - { - throw new RuntimeException("Shouldn't get in here: " + n); - } - @SuppressWarnings("unchecked") - Arg tmp = (Arg) n; - return tmp; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/Substitutor.java b/scribble-core/src/main/java/org/scribble/visit/Substitutor.java deleted file mode 100644 index 0d12d04c0..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/Substitutor.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Map; - -import org.scribble.ast.NonRoleArgNode; -import org.scribble.ast.ScribNode; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.Arg; -import org.scribble.type.kind.NonRoleArgKind; -import org.scribble.type.name.Role; - -public class Substitutor extends AstVisitor -{ - // name in the current protocoldecl scope -> the original name node in the root protocol decl - // Applications of the maps (i.e. substitution) should reconstruct/clone the original nodes - private final Map rolemap; - private final Map, NonRoleArgNode> argmap; - - public Substitutor(Job job, Map rolemap, Map, NonRoleArgNode> argmap) - { - super(job); - this.rolemap = rolemap; - this.argmap = argmap; - } - - @Override - public ScribNode leave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - return visited.substituteNames(this); - } - - public RoleNode getRoleSubstitution(Role role) - { - return this.rolemap.get(role).clone(this.job.af); - } - - public NonRoleArgNode getArgumentSubstitution(Arg arg) - { - return (NonRoleArgNode) this.argmap.get(arg).clone(this.job.af); // Makes new dels that will be discarded in NonRoleParamNode (just as calling the factory manually would) - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/UnfoldingVisitor.java b/scribble-core/src/main/java/org/scribble/visit/UnfoldingVisitor.java deleted file mode 100644 index 538f975ac..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/UnfoldingVisitor.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.Deque; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.Map; -import java.util.Set; - -import org.scribble.ast.Continue; -import org.scribble.ast.ProtocolBlock; -import org.scribble.ast.Recursion; -import org.scribble.ast.ScribNode; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.RecVar; -import org.scribble.visit.env.Env; - -// FIXME: unfolding/unrolling algorithm would be easier if we would use an "affine rec var" normal form: a single rec can have multiple labels, each label used at most once in a continue - -// "Lazily unfolds" each recursion once (by reentering the original rec ast) on reaching a continue -// FIXME: would be better to only unfold "as needed" (unguarded choice-recs) -// N.B. so subclass should manually keep track of when to cut off visiting, as visiting the "unfolding" will eventually reach the same continue (e.g. an unguarded choice-continue) -- currently using pointer equality in e.g. InlinedWFChoice to cut off traversal on reaching the "same" choice again -// Cf. InlinedProtocolUnfolder, statically unfolds unguarded recursions and continues "directly under" choices -public abstract class UnfoldingVisitor> extends InlinedProtocolVisitor -{ - private Map>> recs = new HashMap<>(); - // Stack needed to handle bad reachability cases (e.g. ... continue X; continue Y; -- if rec Y inside unfolding of X, need to push again before popping so Y still in scope for continue) -- since reachability isn't checked until after projection - // Also FIXME: recvar shadowing: though this stack should be enough - private Set unfolded = new HashSet<>(); - - public UnfoldingVisitor(Job job) - { - super(job); - } - - @Override - public ScribNode visit(ScribNode parent, ScribNode child) throws ScribbleException - { - enter(parent, child); - ScribNode visited = visitForUnfolding(parent, child); - return leave(parent, child, visited); - } - - protected ScribNode visitForUnfolding(ScribNode parent, ScribNode child) throws ScribbleException - { - if (child instanceof Continue) - { - Continue cont = (Continue) child; - RecVar rv = cont.recvar.toName(); - if (!this.unfolded.contains(rv)) - { - this.unfolded.add(rv); - // Visiting the children of the seq of the block so as to visit *under the existing env contexts* (i.e. the top Visitor Env) - // N.B. not visiting a clone because subclasses currently using pointer equality to cut off traversal inside the unfolding (e.g. InlinedWFChoiceChecker) - // Also visitChildren, not accept (so not doing enter/exit for the seq) - // Also not returning the seq, just the original continue (cf. do visiting) - //this.recs.get(rv).peek().seq.clone().visitChildren(this); // No: e.g. InlinedWFChoiceChecker uses pointer equality to check if Choice already visited - this.recs.get(rv).peek().seq.visitChildren(this); // FIXME: ok to visit the same AST? any problems with dels/envs? -- maybe do proper equals/hashCode for AST classes - this.unfolded.remove(rv); - return cont; - } - } - return super.visitInlinedProtocol(parent, child); // Not super.visit because that does enter/exit - } - - @Override - protected final void inlinedEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.inlinedEnter(parent, child); - if (child instanceof Recursion) - { - Recursion rec = (Recursion) child; - RecVar rv = rec.recvar.toName(); - if (!this.recs.containsKey(rv)) - { - this.recs.put(rv, new LinkedList<>()); - } - Deque> blocks = this.recs.get(rv); - blocks.push(rec.block); - } - unfoldingEnter(parent, child); - } - - @Override - protected final ScribNode inlinedLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - ScribNode n = unfoldingLeave(parent, child, visited); - if (child instanceof Recursion) - { - Recursion rec = (Recursion) child; - RecVar rv = rec.recvar.toName(); - Deque> blocks = this.recs.get(rv); - blocks.pop(); - /*if (blocks.isEmpty()) // Unnecessary? But tidier? - { - this.recs.remove(rv); - }*/ - } - return super.inlinedLeave(parent, child, n); - } - - protected void unfoldingEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - - } - - protected ScribNode unfoldingLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - return visited; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/context/EGraphBuilder.java b/scribble-core/src/main/java/org/scribble/visit/context/EGraphBuilder.java deleted file mode 100644 index ff33c9ee3..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/context/EGraphBuilder.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context; - -import org.scribble.ast.ScribNode; -import org.scribble.ast.local.LChoice; -import org.scribble.ast.local.LInteractionSeq; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.del.local.LChoiceDel; -import org.scribble.del.local.LInteractionSeqDel; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.model.endpoint.EGraphBuilderUtil; -import org.scribble.visit.NoEnvInlinedProtocolVisitor; - -// Changed from offsetsubprot visitor to inlined visitor to reduce state label accumulation to rec only -- then, wfc-checking for "unguarded" recursive-do-as-continue in choice blocks handled by unfolding inlineds -// Inlined visitor, not unfolding -- but the inlined is already statically unfolded; this just means we don't do a "dynamic" unfolding as part of the AST visit -public class EGraphBuilder extends NoEnvInlinedProtocolVisitor -//public class EndpointGraphBuilder extends NoEnvUnfoldingVisitor // Doesn't work -{ - public final EGraphBuilderUtil util;// = new EGraphBuilderUtil(); - - public EGraphBuilder(Job job) - { - super(job); - this.util = job.newEGraphBuilderUtil(); - } - - // Override visitInlinedProtocol -- not visit, or else enter/exit is lost - @Override - public ScribNode visitInlinedProtocol(ScribNode parent, ScribNode child) throws ScribbleException - { - if (child instanceof LInteractionSeq) - { - return visitOverrideForLInteractionSeq((LProtocolBlock) parent, (LInteractionSeq) child); - } - else if (child instanceof LChoice) - { - return visitOverrideForLChoice((LInteractionSeq) parent, (LChoice) child); - } - else - { - return super.visitInlinedProtocol(parent, child); - } - } - - protected LInteractionSeq visitOverrideForLInteractionSeq(LProtocolBlock parent, LInteractionSeq child) throws ScribbleException - { - return ((LInteractionSeqDel) child.del()).visitForFsmConversion(this, child); - } - - protected LChoice visitOverrideForLChoice(LInteractionSeq parent, LChoice child) - { - return ((LChoiceDel) child.del()).visitForFsmConversion(this, child); - } - - @Override - protected final void inlinedEnter(ScribNode parent, ScribNode child) throws ScribbleException - //protected final void unfoldingEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.inlinedEnter(parent, child); - //super.unfoldingEnter(parent, child); - child.del().enterEGraphBuilding(parent, child, this); - } - - @Override - protected ScribNode inlinedLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - //protected ScribNode unfoldingLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveEGraphBuilding(parent, child, this, visited); - return super.inlinedLeave(parent, child, visited); - //return super.unfoldingLeave(parent, child, visited); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/context/ModuleContextBuilder.java b/scribble-core/src/main/java/org/scribble/visit/context/ModuleContextBuilder.java deleted file mode 100644 index cb66e8d61..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/context/ModuleContextBuilder.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context; - -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ModuleContext; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.visit.AstVisitor; - -// Disambiguates ambiguous PayloadTypeOrParameter names and inserts implicit Scope names -public class ModuleContextBuilder extends AstVisitor -{ - private ModuleContext mcontext; // The "root" Module context (not the "main" module) - - public ModuleContextBuilder(Job job) - { - super(job); - } - - @Override - protected void enter(ScribNode parent, ScribNode child) throws ScribbleException - { - child.del().enterModuleContextBuilding(parent, child, this); - } - - @Override - protected ScribNode leave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - return visited.del().leaveModuleContextBuilding(parent, child, this, visited); - } - - public void setModuleContext(ModuleContext mcontext) - { - this.mcontext = mcontext; - } - - public ModuleContext getModuleContext() - { - return this.mcontext; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/context/ModuleContextVisitor.java b/scribble-core/src/main/java/org/scribble/visit/context/ModuleContextVisitor.java deleted file mode 100644 index fc21b1ea0..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/context/ModuleContextVisitor.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context; - -import org.scribble.ast.Module; -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ModuleContext; -import org.scribble.del.ModuleDel; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.visit.AstVisitor; - -public abstract class ModuleContextVisitor extends AstVisitor -{ - private ModuleContext mcontext; // The "root" module context (different than the front-end "main" module) // Factor up to ModelVisitor? (will be null before context building) - - public ModuleContextVisitor(Job job) - { - super(job); - } - - @Override - protected void enter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.enter(parent, child); - if (child instanceof Module) // Factor out? - { - setModuleContext(((ModuleDel) ((Module) child).del()).getModuleContext()); - } - } - - public ModuleContext getModuleContext() - { - return this.mcontext; - } - - // Factor out -- e.g. some Visitors want to root on ProtocolDecl, not Module - protected void setModuleContext(ModuleContext mcontext) - { - this.mcontext = mcontext; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/context/ProjectedChoiceDoPruner.java b/scribble-core/src/main/java/org/scribble/visit/context/ProjectedChoiceDoPruner.java deleted file mode 100644 index 551258e1d..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/context/ProjectedChoiceDoPruner.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context; - -import java.util.List; - -import org.scribble.ast.ScribNode; -import org.scribble.ast.local.LChoice; -import org.scribble.ast.local.LDo; -import org.scribble.ast.local.LInteractionNode; -import org.scribble.ast.local.LInteractionSeq; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.ast.local.LProtocolDecl; -import org.scribble.ast.name.simple.DummyProjectionRoleNode; -import org.scribble.del.ModuleDel; -import org.scribble.main.Job; -import org.scribble.main.JobContext; -import org.scribble.main.ScribbleException; -import org.scribble.visit.context.env.UnguardedChoiceDoEnv; - -// Basically infers all local choice subject candidates: if *none* are found for a given "choice-unguarded" do-call then the call is pruned (along with parent block and choice as necessary) -// i.e. prune if no choice subject candidates, because that means (passive) role is never enabled and thus not involved -// 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) -public class ProjectedChoiceDoPruner extends ModuleContextVisitor -{ - public ProjectedChoiceDoPruner(Job job) - { - super(job); - } - - - /*@Override - protected ProjectedSubprotocolPruningEnv makeRootProtocolDeclEnv(ProtocolDecl pd) - { - return new ProjectedSubprotocolPruningEnv(); - }*/ - - @Override - public ScribNode visit(ScribNode parent, ScribNode child) throws ScribbleException - { - if (child instanceof LProtocolBlock && parent instanceof LChoice) - { - LChoice lc = (LChoice) parent; - LProtocolBlock lb = (LProtocolBlock) child; - LInteractionSeq lis = lb.getInteractionSeq(); - List ins = lis.getInteractions(); - if (ins.get(0) instanceof LDo) // Unlike GRecursion.prune, to-prune "do" could be followed by a continuation? - { - JobContext jc = this.job.getContext(); - LDo ld = (LDo) ins.get(0); - LProtocolDecl lpd = ld.getTargetProtocolDecl(jc, getModuleContext()); - - UnguardedChoiceDoProjectionChecker checker = new UnguardedChoiceDoProjectionChecker( - this.job, - ((ModuleDel) jc.getModule(ld.proto.toName().getPrefix()).del()).getModuleContext(), - lc); - lpd.accept(checker); - - if ((lc.subj instanceof DummyProjectionRoleNode) && checker.shouldCheckPrune()) - { - UnguardedChoiceDoEnv env = (UnguardedChoiceDoEnv) lpd.def.block.del().env(); // Although AST is cloned, del is the same (HACKY?) - if (env.subjs.isEmpty()) // Prune check - { - return this.job.af.LProtocolBlock(lb.getSource(), - this.job.af.LInteractionSeq(lis.getSource(), ins.subList(1, ins.size()))); // Supports singleton case - } - } - } - } - return super.visit(parent, child); - } - - @Override - //protected void subprotocolEnter(ScribNode parent, ScribNode child) throws ScribbleException - public void enter(ScribNode parent, ScribNode child) throws ScribbleException - { - //super.subprotocolEnter(parent, child); - super.enter(parent, child); - child.del().enterProjectedChoiceDoPruning(parent, child, this); - } - - @Override - //protected ScribNode subprotocolLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - public ScribNode leave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveProjectedChoiceDoPruning(parent, child, this, visited); - //return super.subprotocolLeave(parent, child, visited); - return super.leave(parent, child, visited); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/context/ProjectedChoiceSubjectFixer.java b/scribble-core/src/main/java/org/scribble/visit/context/ProjectedChoiceSubjectFixer.java deleted file mode 100644 index fe6ede9eb..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/context/ProjectedChoiceSubjectFixer.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context; - -import java.util.Deque; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; - -import org.scribble.ast.ScribNode; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.RecVar; -import org.scribble.type.name.Role; - -public class ProjectedChoiceSubjectFixer extends ModuleContextVisitor -{ - private Map> recs = new HashMap>(); - - public ProjectedChoiceSubjectFixer(Job job) - { - super(job); - } - - @Override - protected final void enter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.enter(parent, child); - child.del().enterProjectedChoiceSubjectFixing(parent, child, this); - - /*if (child instanceof LProtocolDecl) - { - System.out.println("aaa:\n" + ((LProtocolDecl) child)); - }*/ - } - - @Override - protected ScribNode leave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveProjectedChoiceSubjectFixing(parent, child, this, visited); - return super.leave(parent, child, visited); - } - - public Role getChoiceSubject(RecVar rv) - { - return this.recs.get(rv).peek(); - } - - public void setChoiceSubject(Role subj) - { - for (Deque rs : this.recs.values()) - { - if (!rs.isEmpty()) // E.g. rec X { ... } rec Y { ... } -- after X, X is still in map but is empty - { - if (rs.peek() == null) - { - rs.pop(); - rs.push(subj); - } - } - } - } - - public void pushRec(RecVar rv) - { - Deque tmp = this.recs.get(rv); - if (tmp == null) - { - tmp = new LinkedList<>(); - this.recs.put(rv, tmp); - } - tmp.push(null); - } - - public void popRec(RecVar rv) - { - this.recs.get(rv).pop(); - } - - public RecVarRole createRecVarRole(RecVar rv) - { - return new RecVarRole(rv.toString()); - } - - public boolean isRecVarRole(Role r) - { - return (r instanceof RecVarRole); - } -} - -class RecVarRole extends Role // HACK for unguarded continues -- but not actually needed? -{ - private static final long serialVersionUID = 1L; - - public RecVarRole(String text) - { - super(text); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/context/ProjectedRoleDeclFixer.java b/scribble-core/src/main/java/org/scribble/visit/context/ProjectedRoleDeclFixer.java deleted file mode 100644 index 39ccb81d8..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/context/ProjectedRoleDeclFixer.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context; - -import org.scribble.ast.ScribNode; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; - -public class ProjectedRoleDeclFixer extends ModuleContextVisitor -{ - public ProjectedRoleDeclFixer(Job job) - { - super(job); - } - - @Override - protected final void enter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.enter(parent, child); - child.del().enterProjectedRoleDeclFixing(parent, child, this); - } - - @Override - protected ScribNode leave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveProjectedRoleDeclFixing(parent, child, this, visited); - return super.leave(parent, child, visited); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/context/Projector.java b/scribble-core/src/main/java/org/scribble/visit/context/Projector.java deleted file mode 100644 index ee5d01c58..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/context/Projector.java +++ /dev/null @@ -1,218 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context; - -import java.util.HashMap; -import java.util.Map; -import java.util.Stack; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.Module; -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ScribNode; -import org.scribble.ast.global.GProtocolDecl; -import org.scribble.ast.name.qualified.LProtocolNameNode; -import org.scribble.ast.name.qualified.ModuleNameNode; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.Local; -import org.scribble.type.kind.ModuleKind; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.LProtocolName; -import org.scribble.type.name.ModuleName; -import org.scribble.type.name.Role; -import org.scribble.visit.EnvVisitor; -import org.scribble.visit.context.env.ProjectionEnv; - -// Uses visitor infrastructure to traverse AST and generate local nodes from global with original nodes unchanged (so does not use normal visitChildren pattern -- env used to pass the working projections) -public class Projector extends EnvVisitor -{ - private Stack selfs = new Stack<>(); // Is a stack needed? roles only pushed from GlobalProtocolDecl, which should be only done once at the root? - - // protocol name is full global protocol name - private Map> projections = new HashMap<>(); - - public Projector(Job job) - { - super(job); - } - - @Override - protected ProjectionEnv makeRootProtocolDeclEnv(ProtocolDecl pd) - { - return new ProjectionEnv(); - } - - @Override - public ScribNode visit(ScribNode parent, ScribNode child) throws ScribbleException - { - // "Override" SubprotocolVisitor visitChildrenInSubprotocols pattern, avoids adding visitForProjection to every ModelNode - // Or else need to build in a "visit override" mechanism into the parent visitors - if (child instanceof GProtocolDecl) - { - return visitOverrideForGProtocolDecl((Module) parent, (GProtocolDecl) child); - } - else - { - return super.visit(parent, child); - } - } - - // Projector uses this to "override" the base SubprotocolVisitor visitChildrenInSubprotocols pattern - // Better to be in the visitor than in the del for visibility of visitor enter/leave -- also localises special visiting pattern inside the visitor, while keeping the del enter/leave methods uniform (e.g. GlobalProtocolDeclDelegate enter/leave relies on the same peekSelf API as for other nodes) - protected GProtocolDecl visitOverrideForGProtocolDecl(Module parent, GProtocolDecl child) throws ScribbleException - { - for (Role self : child.header.roledecls.getRoles()) - { - pushSelf(self); - enter(parent, child); - GProtocolDecl visited = (GProtocolDecl) child.visitChildren(this); // enter/leave around visitChildren for this GlobalProtocolDecl done above -- cf. SubprotocolVisitor.visit - visited = (GProtocolDecl) leave(parent, child, visited); // projection will not change original global protocol (visited can be discarded) - popSelf(); - } - return child; - } - - @Override - protected final void envEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.envEnter(parent, child); - child.del().enterProjection(parent, child, this); - } - - @Override - protected ScribNode envLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveProjection(parent, child, this, visited); - return super.envLeave(parent, child, visited); - } - - public void pushSelf(Role self) - { - this.selfs.push(self); - } - - public Role peekSelf() - { - return this.selfs.peek(); - } - - public Role popSelf() - { - return this.selfs.pop(); - } - - // gpn is full global protocol name, mod is a module with the single local protocol projection - public void addProjection(GProtocolName gpn, Role role, Module mod) - { - Map tmp = this.projections.get(gpn); - if (tmp == null) - { - tmp = new HashMap<>(); - this.projections.put(gpn, tmp); - } - tmp.put(role, mod); - } - - public Map> getProjections() - { - return this.projections; - } - - public static LProtocolName projectSimpleProtocolName(GProtocolName simpname, Role role) - { - return new LProtocolName(simpname.toString() + "_" + role.toString()); - } - - // Role is the target subprotocol parameter (not the current projector self -- actually the self just popped) - public static LProtocolName projectFullProtocolName(GProtocolName fullname, Role role) - { - LProtocolName simplename = projectSimpleProtocolName(fullname.getSimpleName(), role); - ModuleName modname = projectModuleName(fullname.getPrefix(), simplename); - return new LProtocolName(modname, simplename); - } - - // fullname is the un-projected name; localname is the already projected simple name - public static ModuleName projectModuleName(ModuleName fullname, LProtocolName localname) - { - ModuleName simpname = new ModuleName(fullname.getSimpleName().toString() + "_" + localname.toString()); - return new ModuleName(fullname.getPrefix(), simpname); // Supports unary fullname - } - - public static LProtocolNameNode makeProjectedSimpleNameNode(AstFactory af, CommonTree source, GProtocolName simpname, Role role) - { - return (LProtocolNameNode) af.QualifiedNameNode(source, Local.KIND, projectSimpleProtocolName(simpname, role).toString()); - } - - public static LProtocolNameNode makeProjectedFullNameNode(AstFactory af, CommonTree source, GProtocolName fullname, Role role) - { - return (LProtocolNameNode) af.QualifiedNameNode(source, Local.KIND, projectFullProtocolName(fullname, role).getElements()); - } - - // fullname is the un-projected name; localname is the already projected simple name - public static ModuleNameNode makeProjectedModuleNameNode(AstFactory af, CommonTree source, ModuleName fullname, LProtocolName localname) - { - return (ModuleNameNode) af.QualifiedNameNode(source, ModuleKind.KIND, projectModuleName(fullname, localname).getElements()); - } - - // Returns true if should ignore for projection - /*public static boolean prune(LProtocolBlock block) - { - if (block.isEmpty()) - { - return true; - } - List lis = block.getInteractionSeq().getInteractions(); - if (lis.size() > 1) - { - return false; - } - else //if (lis.size() == 1) - { - LInteractionNode lin = lis.get(0); - if (lin instanceof LContinue) - { - return true; - } - else if (lin instanceof MessageTransfer) - { - return false; - } - else - { - if (lin instanceof LChoice) - { - for (LProtocolBlock b : ((LChoice) lin).getBlocks()) - { - if (!prune(b)) - { - return false; - } - } - return true; - } - else if (lin instanceof LRecursion) - { - return prune(((LRecursion) lin).getBlock()); - } - else - { - throw new RuntimeException("TODO: " + lin); - } - } - } - }*/ -} diff --git a/scribble-core/src/main/java/org/scribble/visit/context/ProtocolDeclContextBuilder.java b/scribble-core/src/main/java/org/scribble/visit/context/ProtocolDeclContextBuilder.java deleted file mode 100644 index 858d863be..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/context/ProtocolDeclContextBuilder.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context; - -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.global.GDependencyMap; -import org.scribble.ast.context.local.LDependencyMap; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.LProtocolName; -import org.scribble.type.name.Role; -import org.scribble.visit.NoEnvSubprotocolVisitor; - -// Disambiguates ambiguous PayloadTypeOrParameter names and inserts implicit Scope names -- no: old? -public class ProtocolDeclContextBuilder extends NoEnvSubprotocolVisitor // For transitive dependency collection (cf. NameCollector) -{ - private GDependencyMap gdeps; - private LDependencyMap ldeps; - - public ProtocolDeclContextBuilder(Job job) - { - super(job); - } - - @Override - protected void subprotocolEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.subprotocolEnter(parent, child); - child.del().enterProtocolDeclContextBuilding(parent, child, this); - } - - @Override - protected ScribNode subprotocolLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveProtocolDeclContextBuilding(parent, child, this, visited); - return super.subprotocolLeave(parent, child, visited); - } - - public void clearProtocolDependencies() - { - this.gdeps = new GDependencyMap(); - this.ldeps = new LDependencyMap(); - } - - public void addGlobalProtocolDependency(Role self, GProtocolName gpn, Role target) - { - this.gdeps.addProtocolDependency(self, gpn, target); - } - - public void addLocalProtocolDependency(Role self, LProtocolName lpn, Role target) - { - this.ldeps.addProtocolDependency(self, lpn, target); - } - - public GDependencyMap getGlobalProtocolDependencyMap() - { - return this.gdeps; - } - - public LDependencyMap getLocalProtocolDependencyMap() - { - return this.ldeps; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/context/RecRemover.java b/scribble-core/src/main/java/org/scribble/visit/context/RecRemover.java deleted file mode 100644 index f798d9744..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/context/RecRemover.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context; - -import java.util.HashSet; -import java.util.Set; - -import org.scribble.ast.ScribNode; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.RecVar; -import org.scribble.visit.NoEnvInlinedProtocolVisitor; - -// FIXME: shadowed recvars -public class RecRemover extends NoEnvInlinedProtocolVisitor -{ - private final Set rvs = new HashSet<>(); - - public RecRemover(Job job) - { - super(job); - } - - public void setToRemove(Set rv) - { - this.rvs.clear(); - this.rvs.addAll(rv); - } - - public boolean toRemove(RecVar rv) - { - return this.rvs.contains(rv); - } - - public void remove(RecVar rv) - { - this.rvs.remove(rv); - } - - @Override - public void inlinedEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.inlinedEnter(parent, child); - child.del().enterRecRemoval(parent, child, this); - } - - @Override - public ScribNode inlinedLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveRecRemoval(parent, child, this, visited); - return super.inlinedLeave(parent, child, visited); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/context/UnguardedChoiceDoProjectionChecker.java b/scribble-core/src/main/java/org/scribble/visit/context/UnguardedChoiceDoProjectionChecker.java deleted file mode 100644 index 571e78ca0..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/context/UnguardedChoiceDoProjectionChecker.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context; - -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ModuleContext; -import org.scribble.ast.local.LChoice; -import org.scribble.ast.local.LDo; -import org.scribble.ast.local.LInteractionNode; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.SubprotocolSig; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.ProtocolName; -import org.scribble.visit.SubprotocolVisitor; -import org.scribble.visit.context.env.UnguardedChoiceDoEnv; - -// FIXME: refactor as a choice subject candidate collector (i.e. NameCollector -- thought that is an OffsetSubprotocolCollector, does that make a difference?) -public class UnguardedChoiceDoProjectionChecker extends SubprotocolVisitor -//public class ChoiceUnguardedSubprotocolChecker extends NoEnvSubprotocolVisitor -{ - //private final LChoice cho; // Useless: subprotocovisitor visits a role-substituted clone - - private boolean shouldPrune = false; // OK here, or reinstant in env? - - public UnguardedChoiceDoProjectionChecker(Job job, ModuleContext mcontext, LChoice cho) - { - super(job); - setModuleContext(mcontext); - } - - public void setPruneCheck() - { - this.shouldPrune = true; - } - - public boolean shouldCheckPrune() - { - return this.shouldPrune; - } - - @Override - protected UnguardedChoiceDoEnv makeRootProtocolDeclEnv(ProtocolDecl pd) - { - return new UnguardedChoiceDoEnv(); - } - - @Override - public ScribNode visit(ScribNode parent, ScribNode child) throws ScribbleException - { - if (child instanceof LChoice) - { - LChoice lc = (LChoice) child; - return visitOverrideForLDoPruning(parent, lc); - } - return super.visit(parent, child); - } - - private ScribNode visitOverrideForLDoPruning(ScribNode parent, LChoice lc) throws ScribbleException - { - for (LProtocolBlock b : lc.getBlocks()) - { - LInteractionNode in = b.getInteractionSeq().getInteractions().get(0); - if (in instanceof LDo) - { - LDo ld = (LDo) in; - ProtocolName fullname = getModuleContext().checkProtocolDeclDependencyFullName(ld.proto.toName()); - SubprotocolSig sig = new SubprotocolSig(fullname, ld.roles.getRoles(), ld.args.getArguments()); - - if (sig.equals(getStack().get(0))) // Cf. SubprotocolVisitor.isRootedCycle - { - //if (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 *** - // no?: we don't need to come back to specifically the original choice: we follow the control flow into the target protocoldecl and if we encounter a recursion, regardless of whether it is back to the original choice-do or not, then it's a recursion and that's where the control flow (from this original do) will remain - // 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?) - - { - setPruneCheck(); - return lc; - } - } - } - } - return super.visit(parent, lc); - } - - @Override - protected void subprotocolEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.subprotocolEnter(parent, child); - child.del().enterUnguardedChoiceDoProjectionCheck(parent, child, this); - } - - @Override - protected ScribNode subprotocolLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveUnguardedChoiceDoProjectionCheck(parent, child, this, visited); - return super.subprotocolLeave(parent, child, visited); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/context/env/ProjectionEnv.java b/scribble-core/src/main/java/org/scribble/visit/context/env/ProjectionEnv.java deleted file mode 100644 index 6e799ad2a..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/context/env/ProjectionEnv.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context.env; - -import org.scribble.ast.ScribNode; -import org.scribble.ast.local.LNode; -import org.scribble.visit.env.Env; - -// Could make projection type a class parameter -public class ProjectionEnv extends Env -{ - private ScribNode projection; // Make local // FIXME: need to generalise for do projection (target protocol as well as the do) - - public ProjectionEnv() - { - - } - - @Override - public ProjectionEnv copy() - { - ProjectionEnv copy = new ProjectionEnv(); - copy.projection = this.projection; - return copy; - } - - @Override - public ProjectionEnv enterContext() - { - return copy(); - } - - public ScribNode getProjection() - { - return this.projection; - } - - public ProjectionEnv setProjection(LNode projection) - { - ProjectionEnv copy = new ProjectionEnv(); - copy.projection = projection; - return copy; - } - - @Override - public String toString() - { - return "projection=" + this.projection; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/context/env/UnguardedChoiceDoEnv.java b/scribble-core/src/main/java/org/scribble/visit/context/env/UnguardedChoiceDoEnv.java deleted file mode 100644 index d6bb56385..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/context/env/UnguardedChoiceDoEnv.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.context.env; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import org.scribble.type.name.Role; -import org.scribble.visit.env.Env; - -// Cf. UnfoldingEnv -public class UnguardedChoiceDoEnv extends Env -{ - //private boolean shouldPrune; - public Set subjs; // If well-formed (including wrt. local choice syntax) should be a singleton: but this is currently checked in subsequent choice subject inference pass, not here - - public UnguardedChoiceDoEnv() - { - //this.shouldPrune = true; - this.subjs = new HashSet<>(); - } - - //protected ChoiceUnguardedSubprotocolEnv(boolean shouldPrune, Set subjs) - protected UnguardedChoiceDoEnv(Set subjs) - { - //this.shouldPrune = shouldUnfold; - this.subjs = new HashSet<>(subjs); - } - - @Override - protected UnguardedChoiceDoEnv copy() - { - //return new ChoiceUnguardedSubprotocolEnv(this.shouldPrune, this.subjs); - return new UnguardedChoiceDoEnv(this.subjs); - } - - @Override - public UnguardedChoiceDoEnv enterContext() - { - return copy(); - } - - @Override - public UnguardedChoiceDoEnv mergeContext(UnguardedChoiceDoEnv env) - { - return mergeContexts(Arrays.asList(env)); - } - - @Override - public UnguardedChoiceDoEnv mergeContexts(List envs) - { - UnguardedChoiceDoEnv copy = copy(); - //copy.shouldPrune = (envs.stream().filter((e) -> !e.shouldPrune).count() > 0); // Look for false, cf. UnfoldingEnv - //copy.subjs = envs.stream().flatMap((e) -> e.subjs.stream()).collect(Collectors.toSet()); - copy.subjs.addAll(envs.stream().flatMap((e) -> e.subjs.stream()).collect(Collectors.toSet())); - - //System.out.println("ddd1: " + envs); - //System.out.println("ddd2: " + copy.subjs); - - return copy; - } - - public UnguardedChoiceDoEnv setChoiceSubject(Role r) - { - UnguardedChoiceDoEnv copy = copy(); - if (copy.subjs.isEmpty()) - { - //System.out.println("BBB: " + r); - copy.subjs.add(r); - } - return copy; - } - - /*public boolean shouldPrune() - { - return this.shouldPrune; - } - - public ChoiceUnguardedSubprotocolEnv disablePrune() - { - ChoiceUnguardedSubprotocolEnv copy = copy(); - copy.shouldPrune = false; - return copy; - }*/ - - @Override - public String toString() - { - return super.toString() + ": " + this.subjs; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/env/DummyEnv.java b/scribble-core/src/main/java/org/scribble/visit/env/DummyEnv.java deleted file mode 100644 index 591d409fa..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/env/DummyEnv.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.env; - -public class DummyEnv extends Env -{ - public static final DummyEnv DUMMY = new DummyEnv(); - - protected DummyEnv() - { - - } - - @Override - protected DummyEnv copy() - { - return this; - } - - @Override - public DummyEnv enterContext() - { - return this; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/env/Env.java b/scribble-core/src/main/java/org/scribble/visit/env/Env.java deleted file mode 100644 index 9158ec7ba..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/env/Env.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.env; - -import java.util.List; - -// Consider subclasses like Exception Subclasses, wrt. their purpose in a package -- although using explicit env subpackages (no special API doc treatment, cf. Exceptions) - -// Immutable -// Generic parameter inhibits further subclassing of concrete Env classes -public abstract class Env> -{ - protected Env() - { - - } - - protected abstract E copy(); // Shallow copy - - // Default push for entering a compound interaction context (e.g. used in CompoundInteractionDel via pushVisitorEnv) - public abstract E enterContext(); // copy by default - // FIXME: it's always just copy, so not useful -- e.g., WFChoiceEnv just does enterContext (copy) and then manually enableChoiceSubject - - // Mostly for merging a compound interaction node context into the parent block context - // Usually used in the base compound interaction node del when leaving and restoring the parent env in the visitor env stack (e.g. CompoundInteractionNodeDel for WF-choice) - // By default: merge just discards the argument(s) -- not all EnvVisitors need to merge (e.g. projection) - // FIXME: maybe not "expressive" enough -- e.g. has to be "overloaded" for "horizontal composition" and "vertical parent-child" merging of contexts (e.g. path collection) - protected Env mergeContext(E env) - { - //return mergeContexts(Arrays.asList(env)); - return this; - } - - // Can't use vargs with parameterized types - // Mostly for merging child blocks contexts into the parent compound interaction node context - // Usually used in the parent compound interaction node del to update the parent context after visting each child block before leaving (e.g. GChoiceDel for WF-choice) - // FIXME: deprecate (should use "compose" first on children, then "merge" to parent) -- or make a utility composeAndMerge method - protected Env mergeContexts(List envs) - { - return this; - } - - // FIXME: refactor older Envs to use "merge" for parent-child merging, and "compose" for horizontal merging - protected Env composeContext(E env) - { - return this; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/env/InlineProtocolEnv.java b/scribble-core/src/main/java/org/scribble/visit/env/InlineProtocolEnv.java deleted file mode 100644 index fb646b52b..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/env/InlineProtocolEnv.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.env; - -import org.scribble.ast.ScribNode; - -public class InlineProtocolEnv extends Env -{ - private ScribNode inlined; - - public InlineProtocolEnv() - { - - } - - @Override - protected InlineProtocolEnv copy() - { - return new InlineProtocolEnv(); - } - - @Override - public InlineProtocolEnv enterContext() - { - return copy(); - } - - public ScribNode getTranslation() - { - return this.inlined; - } - - public InlineProtocolEnv setTranslation(ScribNode inlined) - { - InlineProtocolEnv copy = new InlineProtocolEnv(); - copy.inlined = inlined; - return copy; - } - - @Override - public String toString() - { - return "inlined=" + this.inlined; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/env/UnfoldingEnv.java b/scribble-core/src/main/java/org/scribble/visit/env/UnfoldingEnv.java deleted file mode 100644 index 2cd200902..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/env/UnfoldingEnv.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.env; - -import java.util.Arrays; -import java.util.List; - -public class UnfoldingEnv extends Env -{ - private boolean shouldUnfold; // i.e. unguarded choice context - - public UnfoldingEnv() - { - this.shouldUnfold = false; - } - - protected UnfoldingEnv(boolean shouldUnfold) - { - this.shouldUnfold = shouldUnfold; - } - - @Override - protected UnfoldingEnv copy() - { - return new UnfoldingEnv(this.shouldUnfold); - } - - @Override - public UnfoldingEnv enterContext() - { - return copy(); - } - - @Override - public UnfoldingEnv mergeContext(UnfoldingEnv env) - { - return mergeContexts(Arrays.asList(env)); - } - - @Override - public UnfoldingEnv mergeContexts(List envs) - { - UnfoldingEnv copy = copy(); - boolean merge = (envs.stream().filter((e) -> e.shouldUnfold).count() > 0); - copy.shouldUnfold = merge; - return copy; - } - - public boolean shouldUnfold() - { - return this.shouldUnfold; - } - - public UnfoldingEnv pushChoiceParent() - { - UnfoldingEnv copy = copy(); - copy.shouldUnfold = true; - return copy; - } - - public UnfoldingEnv disableUnfold() - { - UnfoldingEnv copy = copy(); - copy.shouldUnfold = false; - return copy; - } - - @Override - public String toString() - { - return super.toString() + ": " + this.shouldUnfold; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/util/MessageIdCollector.java b/scribble-core/src/main/java/org/scribble/visit/util/MessageIdCollector.java deleted file mode 100644 index 92f5598c4..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/util/MessageIdCollector.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.util; - -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ModuleContext; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.MessageId; - -public class MessageIdCollector extends NameCollector> -{ - public MessageIdCollector(Job job, ModuleContext mcontext) - { - super(job, mcontext); - } - - @Override - protected final void offsetSubprotocolEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.offsetSubprotocolEnter(parent, child); - child.del().enterMessageIdCollection(parent, child, this); - } - - @Override - protected ScribNode offsetSubprotocolLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveMessageIdCollection(parent, child, this, visited); - return super.offsetSubprotocolLeave(parent, child, visited); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/util/NameCollector.java b/scribble-core/src/main/java/org/scribble/visit/util/NameCollector.java deleted file mode 100644 index efa8aa762..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/util/NameCollector.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.util; - -import java.util.HashSet; -import java.util.Set; - -import org.scribble.ast.context.ModuleContext; -import org.scribble.main.Job; -import org.scribble.type.name.Name; -import org.scribble.visit.NoEnvOffsetSubprotocolVisitor; - -// Make SubprotocolVisitor? -- should be at least SubprotocolVisitor for get all occurrences up to recursive subprotocols (e.g. role occurrences for protocoldeclcontext) -public abstract class NameCollector> extends NoEnvOffsetSubprotocolVisitor -{ - private Set names = new HashSet<>(); - - public NameCollector(Job job) - { - super(job); - } - - // Can take ModuleContext here, so no need to visit from Module as root -- maybe factor this facility out - // Although has to enter at least at protocoldecl for subprotocol visitor root sig pushing - public NameCollector(Job job, ModuleContext mcontext) - { - super(job); - setModuleContext(mcontext); - } - - public void addName(N name) - { - this.names.add(name); - } - - public void removeName(N name) - { - if (this.names.contains(name)) - { - this.names.remove(name); - } - } - - public Set getNames() - { - return this.names; - } - - public void clear() - { - this.names.clear(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/util/RecVarCollector.java b/scribble-core/src/main/java/org/scribble/visit/util/RecVarCollector.java deleted file mode 100644 index e1438b091..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/util/RecVarCollector.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.util; - -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ModuleContext; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.RecVar; - -// Collects continues (not recs) -public class RecVarCollector extends NameCollector -{ - public RecVarCollector(Job job) - { - super(job); - } - - public RecVarCollector(Job job, ModuleContext mcontext) - { - super(job, mcontext); - } - - @Override - protected final void offsetSubprotocolEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.offsetSubprotocolEnter(parent, child); - if (child instanceof ProtocolDecl) - { - super.clear(); - } - child.del().enterRecVarCollection(parent, child, this); - } - - @Override - protected ScribNode offsetSubprotocolLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveRecVarCollection(parent, child, this, visited); - return super.offsetSubprotocolLeave(parent, child, visited); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/util/RoleCollector.java b/scribble-core/src/main/java/org/scribble/visit/util/RoleCollector.java deleted file mode 100644 index 87a16bfdc..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/util/RoleCollector.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.util; - -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ScribNode; -import org.scribble.ast.context.ModuleContext; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.name.Role; - -// Second pass for ProtocolDeclContext building -// Maybe generalise to integrate enabled message collection? -// NOTE: doesn't collect from choice subjects -public class RoleCollector extends NameCollector -{ - public RoleCollector(Job job) - { - super(job); - } - - public RoleCollector(Job job, ModuleContext mcontext) - { - super(job, mcontext); - } - - @Override - protected final void offsetSubprotocolEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.offsetSubprotocolEnter(parent, child); - if (child instanceof ProtocolDecl) - { - super.clear(); - } - child.del().enterRoleCollection(parent, child, this); - } - - @Override - protected ScribNode offsetSubprotocolLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveRoleCollection(parent, child, this, visited); - return super.offsetSubprotocolLeave(parent, child, visited); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/validation/GProtocolValidator.java b/scribble-core/src/main/java/org/scribble/visit/validation/GProtocolValidator.java deleted file mode 100644 index 9b81d94f9..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/validation/GProtocolValidator.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.validation; - -import org.scribble.ast.ScribNode; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.visit.context.ModuleContextVisitor; - -public class GProtocolValidator extends ModuleContextVisitor -{ - public GProtocolValidator(Job job) - { - super(job); - } - - @Override - public void enter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.enter(parent, child); - child.del().enterValidation(parent, child, this); - } - - @Override - public ScribNode leave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveValidation(parent, child, this, visited); - return super.leave(parent, child, visited); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/wf/DelegationProtocolRefChecker.java b/scribble-core/src/main/java/org/scribble/visit/wf/DelegationProtocolRefChecker.java deleted file mode 100644 index 14c76f71c..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/wf/DelegationProtocolRefChecker.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.wf; - -import java.util.Deque; -import java.util.LinkedList; - -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ScribNode; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.visit.context.ModuleContextVisitor; - -// Checks for recursive protocoldecl dependencies in the presence of delegations (currently, both via the delegation, and in of the protocoldelcs themselves -- FIXME over restrictive) -public class DelegationProtocolRefChecker extends ModuleContextVisitor -{ - private Deque> pds = new LinkedList<>(); // Stack should be unnecessary - // HACK: for DelegationElem recursive protocoldecl dependency checking // FIXME: should factor out more generally - - public DelegationProtocolRefChecker(Job job) - { - super(job); - } - - @Override - public void enter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.enter(parent, child); - if (child instanceof ProtocolDecl) - { - this.pds.push((ProtocolDecl) child); - } - child.del().enterDelegationProtocolRefCheck(parent, child, this); - } - - @Override - public ScribNode leave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveDelegationProtocolRefCheck(parent, child, this, visited); - if (visited instanceof ProtocolDecl) - { - this.pds.pop(); - } - return super.leave(parent, child, visited); - } - - public ProtocolDecl getProtocolDeclOnEntry() // Result of visiting (on leave) will be a different instance - { - return this.pds.peek(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/wf/ExplicitCorrelationChecker.java b/scribble-core/src/main/java/org/scribble/visit/wf/ExplicitCorrelationChecker.java deleted file mode 100644 index 803d854f9..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/wf/ExplicitCorrelationChecker.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.wf; - -import org.scribble.ast.Module; -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ScribNode; -import org.scribble.ast.global.GProtocolDecl; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.Role; -import org.scribble.visit.SubprotocolVisitor; -import org.scribble.visit.wf.env.ExplicitCorrelationEnv; - -//public class ExplicitCorrelationChecker extends InlinedProtocolVisitor -public class ExplicitCorrelationChecker extends SubprotocolVisitor // Need to follow /unfolded/ subprotos (inlined is already unfolded by context building when this pass is run) -{ - public ExplicitCorrelationChecker(Job job) - { - super(job); - } - - - @Override - public ScribNode visit(ScribNode parent, ScribNode child) throws ScribbleException - { - if (child instanceof GProtocolDecl) - { - GProtocolDecl gpd = (GProtocolDecl) child; - if (!gpd.isAuxModifier() && gpd.isExplicitModifier()) - { - Module mod = (Module) parent; - GProtocolName gpn = gpd.getFullMemberName(mod); - for (Role r : gpd.header.roledecls.getRoles()) - { - Module proj = this.job.getContext().getProjection(gpn, r); - proj.accept(this); - } - } - return gpd; - } - return super.visit(parent, child); - } - - @Override - //public void inlinedEnter(ScribNode parent, ScribNode child) throws ScribbleException - public void subprotocolEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - //super.inlinedEnter(parent, child); - super.subprotocolEnter(parent, child); - child.del().enterExplicitCorrelationCheck(parent, child, this); - } - - @Override - //public ScribNode inlinedLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - public ScribNode subprotocolLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveExplicitCorrelationCheck(parent, child, this, visited); - //return super.inlinedLeave(parent, child, visited); - return super.subprotocolLeave(parent, child, visited); - } - - @Override - protected ExplicitCorrelationEnv makeRootProtocolDeclEnv(ProtocolDecl pd) - { - return new ExplicitCorrelationEnv(); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/wf/NameDisambiguator.java b/scribble-core/src/main/java/org/scribble/visit/wf/NameDisambiguator.java deleted file mode 100644 index ccf03a897..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/wf/NameDisambiguator.java +++ /dev/null @@ -1,196 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.wf; - -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.GDelegationElem; -import org.scribble.del.global.GDelegationElemDel; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.NonRoleArgKind; -import org.scribble.type.kind.NonRoleParamKind; -import org.scribble.type.name.Name; -import org.scribble.type.name.RecVar; -import org.scribble.type.name.Role; -import org.scribble.visit.context.ModuleContextVisitor; - -// Disambiguates ambiguous PayloadTypeOrParameter names and inserts implicit Scope names -// Also canonicalises recvars -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) - - public 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 parent, ScribNode child) throws ScribbleException - { - /*if (child instanceof ProtocolDecl) // FIXME: factor out - { - this.root = (ProtocolDecl) child; - }*/ - enter(parent, child); - ScribNode visited = visitForDisamb(parent, child); - return leave(parent, child, visited); - } - - protected ScribNode visitForDisamb(ScribNode parent, ScribNode child) throws ScribbleException - { - if (child instanceof GDelegationElem) - { - //return visitOverrideForDelegationElem(parent, (Do) child); - return ((GDelegationElemDel) child.del()).visitForNameDisambiguation(this, (GDelegationElem) child); - } - else - { - return child.visitChildren(this); - } - } - - @Override - //public NameDisambiguator enter(ModelNode parent, ModelNode child) throws ScribbleException - public void enter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.enter(parent, child); - child.del().enterDisambiguation(parent, child, this); - } - - @Override - public ScribNode leave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveDisambiguation(parent, child, this, visited); - return super.leave(parent, 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 addParameter(Name param, NonRoleParamKind kind) - { - this.params.put(param.toString(), kind); - } - - // name is a simple name (compound names are not ambiguous) - public boolean isBoundParameter(Name name) // ArgKind allows AmbigNames - { - return this.params.containsKey(name.toString()); - } - - public NonRoleParamKind getParameterKind(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-core/src/main/java/org/scribble/visit/wf/ReachabilityChecker.java b/scribble-core/src/main/java/org/scribble/visit/wf/ReachabilityChecker.java deleted file mode 100644 index 5d09e5296..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/wf/ReachabilityChecker.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.wf; - -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ScribNode; -import org.scribble.ast.local.LInteractionSeq; -import org.scribble.ast.local.LProtocolBlock; -import org.scribble.del.local.LInteractionSeqDel; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.visit.UnfoldingVisitor; -import org.scribble.visit.wf.env.ReachabilityEnv; - -public class ReachabilityChecker extends UnfoldingVisitor -{ - public ReachabilityChecker(Job job) - { - super(job); - } - - @Override - protected ReachabilityEnv makeRootProtocolDeclEnv(ProtocolDecl pd) - { - ReachabilityEnv env = new ReachabilityEnv(); - return env; - } - - // Following Projector visit pattern -- for overriding base enter/visit/leave pattern - @Override - protected ScribNode visitForUnfolding(ScribNode parent, ScribNode child) throws ScribbleException - { - if (child instanceof LInteractionSeq) - { - return visitOverrideForLInteractionSequence((LProtocolBlock) parent, (LInteractionSeq) child); - } - else - { - return super.visitForUnfolding(parent, child); - } - } - - protected LInteractionSeq visitOverrideForLInteractionSequence(LProtocolBlock parent, LInteractionSeq child) throws ScribbleException - { - return ((LInteractionSeqDel) child.del()).visitForReachabilityChecking(this, (LInteractionSeq) child); - } - - @Override - protected void unfoldingEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.unfoldingEnter(parent, child); - child.del().enterReachabilityCheck(parent, child, this); - } - - @Override - protected ScribNode unfoldingLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveReachabilityCheck(parent, child, this, visited); - return super.unfoldingLeave(parent, child, visited); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/wf/WFChoiceChecker.java b/scribble-core/src/main/java/org/scribble/visit/wf/WFChoiceChecker.java deleted file mode 100644 index 011f1f11e..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/wf/WFChoiceChecker.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.wf; - -import java.util.HashSet; -import java.util.Set; - -import org.scribble.ast.Choice; -import org.scribble.ast.InteractionSeq; -import org.scribble.ast.ProtocolDecl; -import org.scribble.ast.ScribNode; -import org.scribble.ast.global.GProtocolDecl; -import org.scribble.main.Job; -import org.scribble.main.ScribbleException; -import org.scribble.type.kind.ProtocolKind; -import org.scribble.visit.UnfoldingVisitor; -import org.scribble.visit.wf.env.WFChoiceEnv; - -// Note: now only used for choice subject and enabled checking -// FIXME: refactor as distinct enabling messages checker (cf. GChoiceDel, WFChoicePathChecker) -public class WFChoiceChecker extends UnfoldingVisitor -{ - // N.B. using pointer equality for checking if choice previously visited - // So UnfoldingVisitor cannot visit a clone - // equals method identity not suitable unless Ast nodes record additional info like syntactic position - private Set> visited = new HashSet<>(); - - public WFChoiceChecker(Job job) - { - super(job); - } - - @Override - protected WFChoiceEnv makeRootProtocolDeclEnv(ProtocolDecl pd) - { - return new WFChoiceEnv(new HashSet<>(pd.header.roledecls.getRoles()), - !(pd.isGlobal() && ((GProtocolDecl) pd).modifiers.contains(GProtocolDecl.Modifiers.EXPLICIT))); // FIXME: consider locals; also, explicit modifier should be carried over to local projections - } - - @Override - public ScribNode visit(ScribNode parent, ScribNode child) throws ScribbleException - { - if (child instanceof GProtocolDecl) - { - GProtocolDecl gpd = (GProtocolDecl) child; - if (gpd.isAuxModifier()) - { - return child; // bypass aux protocols // FIXME: integrate bypass functionality into made enter/visit/leave pattern - } - } - - if (this.job.useOldWf) - { - if (child instanceof Choice) // Only needed for old WF (for distinct enabling message checking) // FIXME: maybe move connectedness checking to a separate pass, i.e. vanilla UnfoldingVisitor (if retained as syntactic check) - { - return visitOverrideForChoice((InteractionSeq) parent, (Choice) child); - } - } - return super.visit(parent, child); - } - - private ScribNode visitOverrideForChoice(InteractionSeq parent, Choice child) throws ScribbleException - { - if (child instanceof Choice) - { - Choice cho = (Choice) child; - if (!this.visited.contains(cho)) // ** Old WF breaks connectedness checking, e.g. rec X { choice at A { connect A to B; continue X; } } because of choice visit pruning - { - this.visited.add(cho); - //ScribNode n = cho.visitChildren(this); - ScribNode n = super.visit(parent, child); - this.visited.remove(cho); - return n; - } - else - { - return cho; - } - } - else - { - return super.visit(parent, child); - } - } - - @Override - protected void unfoldingEnter(ScribNode parent, ScribNode child) throws ScribbleException - { - super.unfoldingEnter(parent, child); - child.del().enterInlinedWFChoiceCheck(parent, child, this); - } - - @Override - protected ScribNode unfoldingLeave(ScribNode parent, ScribNode child, ScribNode visited) throws ScribbleException - { - visited = visited.del().leaveInlinedWFChoiceCheck(parent, child, this, visited); - return super.unfoldingLeave(parent, child, visited); - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/wf/env/ExplicitCorrelationEnv.java b/scribble-core/src/main/java/org/scribble/visit/wf/env/ExplicitCorrelationEnv.java deleted file mode 100644 index 8d0caeffa..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/wf/env/ExplicitCorrelationEnv.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.wf.env; - -import java.util.Arrays; -import java.util.List; - -import org.scribble.visit.env.Env; - -public class ExplicitCorrelationEnv extends Env -{ - private boolean canAccept; - - public ExplicitCorrelationEnv() - { - this.canAccept = true; - } - - protected ExplicitCorrelationEnv(boolean canAccept) - { - this.canAccept = canAccept; - } - - @Override - protected ExplicitCorrelationEnv copy() - { - return new ExplicitCorrelationEnv(this.canAccept); - } - - @Override - public ExplicitCorrelationEnv enterContext() - { - return copy(); - } - - @Override - public ExplicitCorrelationEnv mergeContext(ExplicitCorrelationEnv env) - { - return mergeContexts(Arrays.asList(env)); - } - - @Override - public ExplicitCorrelationEnv mergeContexts(List envs) - { - ExplicitCorrelationEnv copy = copy(); - if (copy.canAccept) - { - copy.canAccept = !envs.stream().anyMatch((e) -> !e.canAccept); - } - return copy; - } - - public boolean canAccept() - { - return this.canAccept; - } - - public ExplicitCorrelationEnv disableAccept() - { - if (!this.canAccept) - { - return this; - } - ExplicitCorrelationEnv copy = copy(); - copy.canAccept = false; - return copy; - } - - @Override - public String toString() - { - return super.toString() + ": " + this.canAccept; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/wf/env/ReachabilityEnv.java b/scribble-core/src/main/java/org/scribble/visit/wf/env/ReachabilityEnv.java deleted file mode 100644 index 0b30a9014..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/wf/env/ReachabilityEnv.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.wf.env; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.scribble.type.name.RecVar; -import org.scribble.visit.env.Env; - -public class ReachabilityEnv extends Env -{ - private boolean seqable; - // For checking bad sequencing of unreachable code: false after a continue; true if choice has an exit (false inherited for all other constructs) - private final Set contlabs; // For checking "reachable code" satisfies tail recursion (in the presence of sequencing) - - public ReachabilityEnv() - { - this(true, Collections.emptySet()); - } - - protected ReachabilityEnv(boolean seqable, Set contlabs) - { - this.contlabs = new HashSet(contlabs); - this.seqable = seqable; - } - - @Override - public ReachabilityEnv copy() - { - return new ReachabilityEnv(this.seqable, this.contlabs); - } - - @Override - public ReachabilityEnv enterContext() - { - return copy(); - } - - // Should not be used for single block choice - @Override - public ReachabilityEnv mergeContext(ReachabilityEnv child) - { - return mergeContexts(Arrays.asList(child)); - } - - // Should not be used for Choice - @Override - public ReachabilityEnv mergeContexts(List children) - { - return merge(false, children); - } - - public ReachabilityEnv mergeForChoice(List children) - { - return merge(true, children); - } - - // Does merge depend on choice/par etc? - private ReachabilityEnv merge(boolean isChoice, List children) - { - ReachabilityEnv copy = copy(); - copy.seqable = - (isChoice) - ? children.stream().filter((e) -> e.seqable).count() > 0 - : children.stream().filter((e) -> !e.seqable).count() == 0; - children.stream().forEach((e) -> copy.contlabs.addAll(e.contlabs)); - return copy; - } - - // i.e. control flow has the potential to exit from this context - public boolean isSequenceable() - { - return this.seqable && this.contlabs.isEmpty(); - } - - public ReachabilityEnv addContinueLabel(RecVar recvar) - { - ReachabilityEnv copy = copy(); - copy.seqable = false; - copy.contlabs.add(recvar); - return copy; - } - - public ReachabilityEnv removeContinueLabel(RecVar recvar) - { - ReachabilityEnv copy = copy(); - copy.contlabs.remove(recvar); - return copy; - } -} diff --git a/scribble-core/src/main/java/org/scribble/visit/wf/env/WFChoiceEnv.java b/scribble-core/src/main/java/org/scribble/visit/wf/env/WFChoiceEnv.java deleted file mode 100644 index db03fdc94..000000000 --- a/scribble-core/src/main/java/org/scribble/visit/wf/env/WFChoiceEnv.java +++ /dev/null @@ -1,249 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.wf.env; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.scribble.type.Message; -import org.scribble.type.MessageSig; -import org.scribble.type.Payload; -import org.scribble.type.name.MessageId; -import org.scribble.type.name.Op; -import org.scribble.type.name.Role; -import org.scribble.util.ConnectedMap; -import org.scribble.util.MessageIdMap; -import org.scribble.visit.env.Env; - -public class WFChoiceEnv extends Env -{ - private static final Role DUMMY_ROLE = new Role("__ROLE"); - private static final Op ROOT_OPERATOR = new Op("__ROOT"); - private static final Op SUBJECT_OPERATOR = new Op("__SUBJECT"); - - private static final MessageSig ROOT_MESSAGESIGNATURE = new MessageSig(ROOT_OPERATOR, Payload.EMPTY_PAYLOAD); - private static final MessageSig SUBJECT_MESSAGESIGNATURE = new MessageSig(SUBJECT_OPERATOR, Payload.EMPTY_PAYLOAD); - - // dest -> src -> msg - private MessageIdMap initial; // message transfers recorded here in block envs - //private MessageIdMap initialInterrupts; // interrupts recorded here in interruptible env - - private ConnectedMap connected; - - // FIXME: use roles to initialise MessageIdMap properly, cf. WFBuffers - public WFChoiceEnv(Set roles, boolean implicit) - { - //this(new MessageIdMap(), new MessageIdMap()); - this(new MessageIdMap(), new ConnectedMap(roles, implicit)); - } - - //protected InlinedWFChoiceEnv(MessageIdMap initial, MessageIdMap initialInterrupts) - protected WFChoiceEnv(MessageIdMap initial, ConnectedMap connected) - { - this.initial = new MessageIdMap(initial); - //this.initialInterrupts = new MessageIdMap(initialInterrupts); - this.connected = new ConnectedMap(connected); - } - - @Override - protected WFChoiceEnv copy() - { - //return new InlinedWFChoiceEnv(this.initial, this.initialInterrupts); - return new WFChoiceEnv(this.initial, this.connected); - } - - public WFChoiceEnv clear() - { - WFChoiceEnv copy = copy(); - copy.initial.clear(); - //copy.initialInterrupts.clear(); - return copy; - } - - @Override - public WFChoiceEnv enterContext() - { - //return new InlinedWFChoiceEnv(this.initial, this.initialInterrupts); - return new WFChoiceEnv(this.initial, this.connected); // i.e., copy - } - - @Override - public WFChoiceEnv mergeContext(WFChoiceEnv child) - { - return mergeContexts(Arrays.asList(child)); - } - - // FIXME: refactor to use Stream.reduce? - @Override - public WFChoiceEnv mergeContexts(List children) - { - WFChoiceEnv copy = copy(); - for (WFChoiceEnv child : children) - { - mergeMessageIdMap(this, copy.initial, child.initial); - ////merge(this, copy.initialInterrupts, child.initialInterrupts); - //merge(this, copy.connected, child.connected); - } - - // FIXME: refactor, cf. mergeMessageIdMap - ConnectedMap cm = children.get(0).getConnected(); - for (WFChoiceEnv e : children.subList(1, children.size())) - { - cm = cm.merge(e.getConnected()); - } - copy.connected = cm; - return copy; - } - - // Pre: foo is orig.copy().initial -- orig is "parent" - // Updates running according to state of orig and child - private static void mergeMessageIdMap(WFChoiceEnv orig, MessageIdMap running, MessageIdMap child) - { - for (Role dest : child.getDestinations()) - { - for (Role src : child.getSources(dest)) - { - if (!orig.isEnabled(dest)) - { - running.putMessages(dest, src, child.getMessages(dest, src)); - } - } - } - } - - /*// FIXME: factor out with MessageIdMap - private static void merge(WFChoiceEnv parent, ConnectedMap foo, ConnectedMap child) - { - for (Role dest : child.getDestinations()) - { - for (Role src : child.getSources(dest)) - { - //if (!parent.isConnected(src, dest)) - { - // If not previously connected, update connected according to latest state -- No: also need to write disconnected (if parent is connected) - foo.setConnected(dest, src, child.isConnected(dest, src)); - } - } - } - }*/ - - public WFChoiceEnv enableRoleForRootProtocolDecl(Role role) - { - return addMessage(WFChoiceEnv.DUMMY_ROLE, role, WFChoiceEnv.ROOT_MESSAGESIGNATURE); - } - - public WFChoiceEnv enableChoiceSubject(Role role) - { - return addMessage(WFChoiceEnv.DUMMY_ROLE, role, WFChoiceEnv.SUBJECT_MESSAGESIGNATURE); - } - - public WFChoiceEnv connect(Role src, Role dest) - { - WFChoiceEnv copy = copy(); - copy.connected.connect(src, dest); - return copy; - } - - public WFChoiceEnv disconnect(Role src, Role dest) - { - WFChoiceEnv copy = copy(); - copy.connected.disconnect(src, dest); - return copy; - } - - // The "main" public routine - // Rename: more like enable-if-not-already - public WFChoiceEnv addMessage(Role src, Role dest, Message msg) - { - WFChoiceEnv copy = copy(); - addMessages(copy.initial, src, dest, Arrays.asList(msg.getId())); - return copy; - } - - /*public WFChoiceEnv removeMessage(Role src, Role dest, Message msg) - { - WFChoiceEnv copy = copy(); - copy.initial.removeMessage(dest, src, msg.getId()); - return copy; - } - - public WFChoiceEnv disableRole(Role r) - { - WFChoiceEnv copy = copy(); - for (...) - { - copy.initial.removeMessage(dest, src, ...); - } - return copy; - }*/ - - // FIXME: List/Set argument - // Means: record message as initial enabling message if dest not already enabled - private static void addMessages(MessageIdMap map, Role src, Role dest, List> msgs) - { - if (!map.containsDestination(dest)) // FIXME: factor out isEnabled - { - map.putMessages(dest, src, new HashSet<>(msgs)); - } - } - - /*public InlinedWFChoiceEnv addInterrupt(Role src, Role dest, Message msg) - { - InlinedWFChoiceEnv copy = copy(); - if (!copy.initial.containsLeftKey(dest)) - { - copy.initialInterrupts.putMessage(dest, src, msg.getId()); - } - return copy; - }*/ - - public boolean isEnabled(Role role) - { - return this.initial.containsDestination(role); - } - - public MessageIdMap getEnabled() - { - MessageIdMap tmp = new MessageIdMap(this.initial); - //tmp.merge(this.initialInterrupts); - return tmp; - } - - public ConnectedMap getConnected() - { - ConnectedMap tmp = new ConnectedMap(this.connected); - return tmp; - } - - /*public WFChoiceEnv setConnected(ConnectedMap cm) - { - WFChoiceEnv copy = copy(); - copy.connected = cm; - return copy; - }*/ - - public boolean isConnected(Role r1, Role r2) - { - return this.connected.isConnected(r1, r2); - } - - @Override - public String toString() - { - //return "initial=" + this.initial.toString() + ", initialInterrupts=" + this.initialInterrupts.toString(); - return "initial=" + this.initial.toString(); - } -} diff --git a/scribble-core/src/test/scrib/demo/fase17/travel/TravelAgent.scr b/scribble-core/src/test/scrib/demo/fase17/travel/TravelAgent.scr deleted file mode 100644 index 88cc4eeae..000000000 --- a/scribble-core/src/test/scrib/demo/fase17/travel/TravelAgent.scr +++ /dev/null @@ -1,45 +0,0 @@ -//$ bin/scribblec.sh scribble-core/src/test/scrib/demo/fase17/travel/TravelAgent.scr -ip scribble-core/src/test/scrib/ -d scribble-core/src/test/scrib -api TravelAgent C -V -//$ javadoc -cp scribble-cli/target/classes/';'scribble-core/target/classes';'scribble-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;'scribble-core/src/test/scrib -subpackages demo.fase17.travel.TravelAgent.TravelAgent -d test/doc/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-core/src/test/scrib/demo/fase17/travel2/Travel2C.java b/scribble-core/src/test/scrib/demo/fase17/travel2/Travel2C.java deleted file mode 100644 index 4f3ccbf68..000000000 --- a/scribble-core/src/test/scrib/demo/fase17/travel2/Travel2C.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 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.net.Buf; -import org.scribble.net.ObjectStreamFormatter; -import org.scribble.net.session.ExplicitEndpoint; -import org.scribble.net.session.SocketChannelEndpoint; - -import demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2; -import demo.fase17.travel2.TravelAgent2.TravelAgent2.channels.C.TravelAgent2_C_1; -import demo.fase17.travel2.TravelAgent2.TravelAgent2.channels.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) - .connect(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) - .connect(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-core/src/test/scrib/demo/fase17/travel2/TravelAgent2.scr b/scribble-core/src/test/scrib/demo/fase17/travel2/TravelAgent2.scr deleted file mode 100644 index 3d6162652..000000000 --- a/scribble-core/src/test/scrib/demo/fase17/travel2/TravelAgent2.scr +++ /dev/null @@ -1,52 +0,0 @@ -//$ bin/scribblec.sh modules/core/src/test/scrib/demo/fase17/travel2/TravelAgent2.scr -ip modules/core/src/test/scrib/ -d modules/core/src/test/scrib -nocorrelation -//$ 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 -subpackages demo.fase17.travel2.TravelAgent2.TravelAgent2 -d test/doc/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-core/src/test/scrib/test/test1/MyC.java b/scribble-core/src/test/scrib/test/test1/MyC.java deleted file mode 100644 index 5f13c743a..000000000 --- a/scribble-core/src/test/scrib/test/test1/MyC.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT 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.net.Buf; -import org.scribble.net.ObjectStreamFormatter; -import org.scribble.net.session.MPSTEndpoint; -import org.scribble.net.session.SocketChannelEndpoint; - -import test.test1.Test1.Proto1.Proto1; -import test.test1.Test1.Proto1.channels.C.Proto1_C_1; -import test.test1.Test1.Proto1.channels.C.Proto1_C_2; -import test.test1.Test1.Proto1.roles.C; - -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.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) - .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-core/src/test/scrib/test/test1/MyS.java b/scribble-core/src/test/scrib/test/test1/MyS.java deleted file mode 100644 index 42331acf0..000000000 --- a/scribble-core/src/test/scrib/test/test1/MyS.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 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.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 test.test1.Test1.Proto1.Proto1; -import test.test1.Test1.Proto1.channels.S.EndSocket; -import test.test1.Test1.Proto1.channels.S.Proto1_S_1; -import test.test1.Test1.Proto1.channels.S.Proto1_S_2_Handler; -import test.test1.Test1.Proto1.channels.S.Proto1_S_3; -import test.test1.Test1.Proto1.channels.S.ioifaces.Branch_S_C_2_Integer__C_4; -import test.test1.Test1.Proto1.channels.S.ioifaces.Handle_S_C_2_Integer__C_4; -import test.test1.Test1.Proto1.channels.S.ioifaces.Receive_S_C_1; -import test.test1.Test1.Proto1.channels.S.ioifaces.Select_S_C_3_Integer; -import test.test1.Test1.Proto1.channels.S.ioifaces.Succ_In_C_2_Integer; -import test.test1.Test1.Proto1.channels.S.ioifaces.Succ_In_C_4; -import test.test1.Test1.Proto1.ops._2; -import test.test1.Test1.Proto1.ops._4; -import test.test1.Test1.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()); - } - 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("Done"); - 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); - } - 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 arg1) throws ScribbleRuntimeException, IOException, ClassNotFoundException - { - System.out.println("Redo: " + arg1.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 ScribbleRuntimeException, IOException, ClassNotFoundException - { - schan.to(EndSocket.cast).end(); - System.out.println("Done"); - } -} diff --git a/scribble-core/src/test/scrib/tmp/Test.scr b/scribble-core/src/test/scrib/tmp/Test.scr deleted file mode 100644 index 2ffe71835..000000000 --- a/scribble-core/src/test/scrib/tmp/Test.scr +++ /dev/null @@ -1,3508 +0,0 @@ -//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.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 - -//$ bin/scribblec.sh -ip scribble-core/src/test/scrib/ -d scribble-core/src/test/scrib/tmp/ scribble-core/src/test/scrib/tmp/Test.scr -//$ bin/scribblec.sh -ip scribble-core/src/test/scrib/ -d scribble-core/src/test/scrib/tmp/ scribble-core/src/test/scrib/tmp/Test.scr -api Proto1 B - - -//http://sandbox.kidstrythisathome.com/erdos/ - - -module Test; - -// replace a lot of FACTORY name calls by clone -// -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 - - -// FIXME TODO: port forwarding version of P2 -- funny case of "session" persisting over full disconnect, should/how to correlate? - - - - - - - - - - - - - - - - - - - -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; - } - } -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/* -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-demos/pom.xml b/scribble-demos/pom.xml index 1cd93548a..7e15c327b 100644 --- a/scribble-demos/pom.xml +++ b/scribble-demos/pom.xml @@ -2,16 +2,10 @@ 4.0.0 + + scribble-demos jar - scribble-demos - - - org.scribble - parent - 0.4.4-SNAPSHOT - ../pom.xml - @@ -28,8 +22,17 @@ + + org.scribble + parent + 0.5.1-SNAPSHOT + ../pom.xml + + + + com.mycila license-maven-plugin @@ -43,9 +46,16 @@ **/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 index 24407f071..a1fc9349d 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLong.scr +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLong.scr @@ -2,6 +2,9 @@ * 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 + * */ @@ -42,7 +45,7 @@ sig "betty16.lec1.httplong.message.client.DoNotTrack" sig "betty16.lec1.httplong.message.client.Connection" from "betty16/lec1/httplong/message/Connection.java" - as CONNECTION; // Connection: keep-alive + as CONN; // Connection: keep-alive sig "betty16.lec1.httplong.message.client.UpgradeInsecureRequests" from "betty16/lec1/httplong/message/UpgradeInsecureRequests.java" @@ -51,7 +54,15 @@ sig "betty16.lec1.httplong.message.client.UpgradeInsecureRequests" 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" @@ -103,7 +114,7 @@ sig "betty16.lec1.httplong.message.server.ContentType" sig "betty16.lec1.httplong.message.server.Via" from "betty16/lec1/httplong/message/Via.java" - as VIA; // Via: 1.1 www.doc.ic.ac.uk + as VIA; // Via: 1.1 www.doc.ic.ac.uk global protocol Http(role C, role S) { @@ -134,7 +145,7 @@ aux global protocol Request(role C, role S) { DNT from C to S; // DNT: 1 continue X; } or { - CONNECTION from C to S; // Connection: keep-alive + CONN from C to S; // Connection: keep-alive continue X; } or { UPGRADEIR from C to S; // Upgrade-Insecure-Requests: 1 @@ -142,7 +153,13 @@ aux global protocol Request(role C, role S) { } 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 { + } 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; } } diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLongC.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLongC.java index c309aa88b..787219c6e 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLongC.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLongC.java @@ -30,57 +30,44 @@ import static betty16.lec1.httplong.HttpLong.Http.Http._200; import static betty16.lec1.httplong.HttpLong.Http.Http._404; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.EndSocket; -import betty16.lec1.httplong.HttpLong.Http.channels.C.Http_C_1; -import betty16.lec1.httplong.HttpLong.Http.channels.C.Http_C_3; -import betty16.lec1.httplong.HttpLong.Http.channels.C.Http_C_4_Cases; -import betty16.lec1.httplong.HttpLong.Http.channels.C.Http_C_5; -import betty16.lec1.httplong.HttpLong.Http.channels.C.Http_C_5_Cases; 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 = "www.doc.ic.ac.uk"; int port = 80; - //String host = "localhost"; int port = 8080; + 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.connect(S, SocketChannelEndpoint::new, host, port); - new HttpLongC().run(new Http_C_1(client), host); + 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) throws Exception { - return doResponse(doRequest(c, host)); + 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) throws Exception { - return c1.send(S, new RequestLine("/~rhu/", "1.1")) + 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("")); } diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLongS.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLongS.java index 7cc4ad264..5b2f03b9b 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLongS.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLongS.java @@ -18,35 +18,46 @@ 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.CONNECTION; +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.COOKIE; 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.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.scribsock.ScribServerSocket; -import org.scribble.runtime.net.scribsock.SocketChannelServer; -import org.scribble.runtime.net.session.MPSTEndpoint; +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.channels.S.EndSocket; -import betty16.lec1.httplong.HttpLong.Http.channels.S.Http_S_1; -import betty16.lec1.httplong.HttpLong.Http.channels.S.Http_S_2; -import betty16.lec1.httplong.HttpLong.Http.channels.S.Http_S_2_Cases; 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 @@ -54,12 +65,14 @@ 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())) { + try (MPSTEndpoint server = new MPSTEndpoint<>(http, S, + new HttpLongMessageFormatter())) { server.accept(ss, C); run(new Http_S_1(server)); } - catch (IOException | ClassNotFoundException | ScribbleRuntimeException e) + catch (IOException | ClassNotFoundException + | ScribRuntimeException e) { e.printStackTrace(); } @@ -67,7 +80,8 @@ public static void main(String[] args) throws Exception } } - private static EndSocket run(Http_S_1 s1) throws ClassNotFoundException, ScribbleRuntimeException, IOException { + 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); @@ -89,12 +103,15 @@ private static EndSocket run(Http_S_1 s1) throws ClassNotFoundException, Scribbl .send(C, new ContentLength(body.length())) .send(C, new Body(body)); } - 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 COOKIE: s2 = cases.receive(COOKIE, buf); break; - case HOST: s2 = cases.receive(HOST, buf); break; - case USERA: s2 = cases.receive(USERA, buf); break; + 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/HeaderField.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/HeaderField.java index 0ca331213..f8869fc91 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/HeaderField.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/HeaderField.java @@ -13,7 +13,7 @@ */ package betty16.lec1.httplong.message; -import org.scribble.type.name.Op; +import org.scribble.core.type.name.Op; public abstract class HeaderField extends HttpLongMessage { 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 index c6f9fcb6d..ea02f8a8f 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/HttpLongMessage.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/HttpLongMessage.java @@ -13,8 +13,8 @@ */ package betty16.lec1.httplong.message; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.type.name.Op; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.core.type.name.Op; import betty16.lec1.httplong.HttpLong.Http.Http; @@ -23,6 +23,7 @@ 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"; @@ -36,6 +37,8 @@ public abstract class HttpLongMessage extends ScribMessage 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"; @@ -69,7 +72,9 @@ public String getBody() public byte[] toBytes() { - return (getOpString(this.op) + getBody() + HttpLongMessage.CRLF).getBytes(HttpLongMessageFormatter.cs); // Can give "utf-8" as arg directly + return (getOpString(this.op) + getBody() + HttpLongMessage.CRLF) + .getBytes(HttpLongMessageFormatter.cs); + // Can give "utf-8" as arg directly } @Override 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 index 3f6412b66..8a46665ac 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/HttpLongMessageFormatter.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/HttpLongMessageFormatter.java @@ -19,32 +19,10 @@ import java.nio.ByteBuffer; import java.nio.charset.Charset; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.runtime.net.ScribMessageFormatter; - -import betty16.lec1.httplong.message.client.Accept; -import betty16.lec1.httplong.message.client.AcceptEncoding; -import betty16.lec1.httplong.message.client.AcceptLanguage; -import betty16.lec1.httplong.message.client.Connection; -import betty16.lec1.httplong.message.client.DoNotTrack; -import betty16.lec1.httplong.message.client.Host; -import betty16.lec1.httplong.message.client.RequestLine; -import betty16.lec1.httplong.message.client.UpgradeInsecureRequests; -import betty16.lec1.httplong.message.client.Cookie; -import betty16.lec1.httplong.message.client.UserAgent; -import betty16.lec1.httplong.message.server.AcceptRanges; -import betty16.lec1.httplong.message.server.ContentLength; -import betty16.lec1.httplong.message.server.ContentType; -import betty16.lec1.httplong.message.server.Date; -import betty16.lec1.httplong.message.server.ETag; -import betty16.lec1.httplong.message.server.HttpVersion; -import betty16.lec1.httplong.message.server.LastModified; -import betty16.lec1.httplong.message.server.Server; -import betty16.lec1.httplong.message.server.StrictTransportSecurity; -import betty16.lec1.httplong.message.server.Vary; -import betty16.lec1.httplong.message.server.Via; -import betty16.lec1.httplong.message.server._200; -import betty16.lec1.httplong.message.server._404; +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 { @@ -91,7 +69,7 @@ public ScribMessage fromBytes(ByteBuffer bb) throws IOException, ClassNotFoundEx //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++) + for (int i = 0; i < this.len; i++) // CHECKME: Client-side len out by 1? e.g., example.com { sb.append((char) bb.get()); } @@ -170,7 +148,7 @@ else if (front.equals(HttpLongMessage.HTTP)) 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.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); @@ -179,7 +157,9 @@ else if (front.equals(HttpLongMessage.HTTP)) 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); @@ -194,7 +174,11 @@ else if (front.equals(HttpLongMessage.HTTP)) 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); + default: { + //throw new RuntimeException("Cannot parse header field: " + line); + System.err.println("Cannot parse header field, attempting to skip: " + line); + return fromBytes(bb); + } } } else @@ -274,6 +258,13 @@ private int isStatusCode(String front) + + + + + + + // FIXME: delete @Deprecated @Override public void writeMessage(DataOutputStream dos, ScribMessage m) throws IOException 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 index 96bbc325e..d7eba14ef 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/StartLine.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/StartLine.java @@ -13,7 +13,7 @@ */ package betty16.lec1.httplong.message; -import org.scribble.type.name.Op; +import org.scribble.core.type.name.Op; public abstract class StartLine extends HttpLongMessage { 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 index 1ed237ee7..6fe6f347c 100644 --- 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 @@ -22,6 +22,6 @@ public class Connection extends HeaderField public Connection(String text) { - super(Http.CONNECTION, 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/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/server/StatusCode.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/StatusCode.java index 90c18d9c8..376d0bf23 100644 --- 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 @@ -13,7 +13,7 @@ */ package betty16.lec1.httplong.message.server; -import org.scribble.type.name.Op; +import org.scribble.core.type.name.Op; import betty16.lec1.httplong.message.HttpLongMessage; diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShort.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShort.scr index f7d230c9a..fbda13229 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShort.scr +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShort.scr @@ -3,7 +3,7 @@ * * ./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 + * $ 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 * */ diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShortC.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShortC.java index 8ddf10b9e..789a31ac0 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShortC.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShortC.java @@ -13,16 +13,18 @@ */ package betty16.lec1.httpshort; -import static betty16.lec1.httpshort.HttpShort.Http.Http.*; +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.Buf; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.EndSocket; -import betty16.lec1.httpshort.HttpShort.Http.channels.C.Http_C_1; 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; @@ -31,80 +33,25 @@ 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 = "www.doc.ic.ac.uk"; int port = 80; - //String host = "summerschool2016.behavioural-types.eu"; int port = 80; - //String host = "localhost"; int port = 8080; + 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.connect(S, SocketChannelEndpoint::new, host, port); - new HttpShortC().run(new Http_C_1(client)); + client.request(S, SocketChannelEndpoint::new, host, port); + new HttpShortC().run(new Http_C_1(client), host, file); } } - - - - - - - - - - - - - private EndSocket run(Http_C_1 c) throws Exception { - Buf buf = new Buf<>(); - - EndSocket end = null; - /*c.send(S, new Response("", "")) - .receive(S, Response, buf);*/ - - System.out.println("Response:\n" + buf.val); - - return end; - } - - - - - - - - - - - - - - - - - //c.send(S, new Request("/~rhu/", "1.1", "www.doc.ic.ac.uk")).receive(S, Response, buf); - - - - - - - - - - /* - private EndSocket run2(Http_C_1 c1, String host) throws Exception { + private EndSocket run(Http_C_1 c1, String host, String file) throws Exception { Buf buf = new Buf<>(); EndSocket end = - c.send(S, new Request("/~rhu/", "1.1", host)) - //.send(S, new Request("/~rhu/", "1.1", host)) + c1.send(S, new Request(file, "1.1", host)) .receive(S, Response, buf); System.out.println("Response:\n" + buf.val); return end; } - //*/ - //.send(S, new Response("1.1", "..body..")) - //.send(S, new Request("/~rhu/", "1.1", host)) - //.receive(S, RESPONSE, new Buf<>()); } diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShortS.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShortS.java index b1a0a8da3..bbb62f6de 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShortS.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShortS.java @@ -19,16 +19,16 @@ import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.scribsock.ScribServerSocket; -import org.scribble.runtime.net.scribsock.SocketChannelServer; -import org.scribble.runtime.net.session.MPSTEndpoint; +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.channels.S.Http_S_1; -import betty16.lec1.httpshort.HttpShort.Http.channels.S.Http_S_2; 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; @@ -39,12 +39,13 @@ 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())) { + try (MPSTEndpoint server = new MPSTEndpoint<>(http, S, + new HttpShortMessageFormatter())) { server.accept(ss, C); run(new Http_S_1(server)); } - catch (IOException | ClassNotFoundException | ScribbleRuntimeException e) + catch (IOException | ClassNotFoundException | ScribRuntimeException e) { e.printStackTrace(); } @@ -52,7 +53,8 @@ public static void main(String[] args) throws IOException { } } - private static void run(Http_S_1 s1) throws ClassNotFoundException, ScribbleRuntimeException, IOException { + 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); 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 index e2386de26..424e90e63 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/message/HttpShortMessage.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/message/HttpShortMessage.java @@ -13,8 +13,8 @@ */ package betty16.lec1.httpshort.message; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.type.name.Op; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.core.type.name.Op; import betty16.lec1.httpshort.HttpShort.Http.Http; 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 index 4a24f2615..6e3f45924 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/message/HttpShortMessageFormatter.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/message/HttpShortMessageFormatter.java @@ -20,8 +20,8 @@ import java.nio.charset.Charset; import java.util.Arrays; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.runtime.net.ScribMessageFormatter; +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; @@ -43,7 +43,8 @@ public byte[] toBytes(ScribMessage m) throws IOException } @Override - public ScribMessage fromBytes(ByteBuffer bb) throws IOException, ClassNotFoundException + public ScribMessage fromBytes(ByteBuffer bb) + throws IOException, ClassNotFoundException { bb.flip(); int rem = bb.remaining(); @@ -53,7 +54,8 @@ public ScribMessage fromBytes(ByteBuffer bb) throws IOException, ClassNotFoundEx return null; } - String curr = new String(Arrays.copyOf(bb.array(), bb.remaining()), HttpShortMessageFormatter.cs); + String curr = new String(Arrays.copyOf(bb.array(), bb.remaining()), + HttpShortMessageFormatter.cs); String endOfHeaders = HttpShortMessage.CRLF + HttpShortMessage.CRLF; if (!curr.contains(endOfHeaders)) { @@ -69,8 +71,11 @@ public ScribMessage fromBytes(ByteBuffer bb) throws IOException, ClassNotFoundEx 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()); + 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(); @@ -151,7 +156,12 @@ private static HttpShortMessage parseRequest(String msg) 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)); + //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); } @@ -160,7 +170,8 @@ private static HttpShortMessage parseRequest(String msg) { throw new RuntimeException("Shouldn't get in here: " + msg); } - return new Request(get, http, host, userA, accept, acceptL, acceptE, dnt, connection, upgradeIR, cookie); + return new Request(get, http, host, userA, accept, acceptL, acceptE, dnt, + connection, upgradeIR, cookie); } private static HttpShortMessage parseResponse(String msg) @@ -231,18 +242,24 @@ private static HttpShortMessage parseResponse(String msg) 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()); + 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); + return new Response(httpv, ack, date, server, strictTS, lastMod, eTag, + acceptR, contentL, vary, contentT, via, body); } - // FIXME: delete + + + + // TODO: delete @Deprecated @Override public void writeMessage(DataOutputStream dos, ScribMessage m) throws IOException { 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 index e9df2a159..b8fef7cdb 100644 --- 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 @@ -20,6 +20,7 @@ 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"; @@ -29,6 +30,8 @@ public class Request extends HttpShortMessage { 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)); 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 index 3616531c5..aa1cd2468 100644 --- 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 @@ -20,6 +20,7 @@ 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"; diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/LocatedChoice2.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/LocatedChoice2.scr index 456c29098..3978d0892 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/LocatedChoice2.scr +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/LocatedChoice2.scr @@ -1,5 +1,6 @@ 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 { diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Messaging.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Messaging.scr index b6f80e7d0..0c30b83fb 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Messaging.scr +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Messaging.scr @@ -1,8 +1,8 @@ module betty16.lec1.misc.Messaging; -type "java.lang.Integer" from "rt.jar" as Int; -type "java.lang.String" from "rt.jar" as String; +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) { diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/nego/Negotiate.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/nego/Negotiate.scr index 5157b1ecf..adbf5e88a 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec1/nego/Negotiate.scr +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/nego/Negotiate.scr @@ -8,7 +8,7 @@ module betty16.lec1.nego.Negotiate; -type "test.nego.SAP" from "test/nego/SAP.java" as SAP; +data "test.nego.SAP" from "test/nego/SAP.java" as SAP; // C = Consumer, P = Producer diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/Adder.scr b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/Adder.scr index f6e4d66d8..9216608b8 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/Adder.scr +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/Adder.scr @@ -7,9 +7,6 @@ * (2) Build Endpoint FSM for C: * $ ./scribblec.sh scribble-demos/scrib/betty16/src/betty16/lec2/adder/Adder.scr -fsm Adder C * - * (3) Generate "Session API" for Adder: - * $ ./scribblec.sh -d scribble-demos/scrib/betty16/src/ scribble-demos/scrib/betty16/src/betty16/lec2/adder/Adder.scr -session Adder - * * (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 * @@ -22,7 +19,7 @@ module betty16.lec2.adder.Adder; -type "java.lang.Integer" from "rt.jar" as Integer; +data "java.lang.Integer" from "rt.jar" as Integer; global protocol Adder(role C, role S) { diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderC1.java b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderC1.java index 7a8900846..57a379759 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderC1.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderC1.java @@ -19,21 +19,22 @@ import static betty16.lec2.adder.Adder.Adder.Adder.Res; import static betty16.lec2.adder.Adder.Adder.Adder.S; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.ObjectStreamFormatter; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Adder_C_1; 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.connect(S, SocketChannelEndpoint::new, "localhost", 8888); + try (MPSTEndpoint client = new MPSTEndpoint<>(adder, C, + new ObjectStreamFormatter())) { + client.request(S, SocketChannelEndpoint::new, "localhost", 8888); System.out.println("C: " + new AdderC1().run(client)); } } diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderC2.java b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderC2.java index 49839750b..e9d9968e2 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderC2.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderC2.java @@ -19,21 +19,22 @@ import static betty16.lec2.adder.Adder.Adder.Adder.Res; import static betty16.lec2.adder.Adder.Adder.Adder.S; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.ObjectStreamFormatter; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Adder_C_1; 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.connect(S, SocketChannelEndpoint::new, "localhost", 8888); + try (MPSTEndpoint client = new MPSTEndpoint<>(adder, C, + new ObjectStreamFormatter())) { + client.request(S, SocketChannelEndpoint::new, "localhost", 8888); System.out.println("C: " + new AdderC2().run(client)); } } diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderS1.java b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderS1.java index 6bd44aad5..e7c7e8f86 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderS1.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderS1.java @@ -21,17 +21,17 @@ import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -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 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.channels.S.Adder_S_1; -import betty16.lec2.adder.Adder.Adder.channels.S.Adder_S_1_Cases; 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 { @@ -39,10 +39,11 @@ 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())) { + try (MPSTEndpoint server = new MPSTEndpoint<>(adder, S, + new ObjectStreamFormatter())) { server.accept(ss, C); new AdderS1().run(new Adder_S_1(server)); - } catch (ScribbleRuntimeException | IOException | ClassNotFoundException e) { + } catch (ScribRuntimeException | IOException | ClassNotFoundException e) { e.printStackTrace(); } } diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderS2.java b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderS2.java index d5e9d1e43..bd64eaade 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderS2.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderS2.java @@ -20,21 +20,21 @@ import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -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 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.channels.S.Adder_S_1; -import betty16.lec2.adder.Adder.Adder.channels.S.Adder_S_1_Handler; -import betty16.lec2.adder.Adder.Adder.channels.S.Adder_S_2; -import betty16.lec2.adder.Adder.Adder.channels.S.Adder_S_3; 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 { @@ -42,11 +42,12 @@ 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())) { + try (MPSTEndpoint server = new MPSTEndpoint<>(adder, S, + new ObjectStreamFormatter())) { server.accept(ss, C); new Adder_S_1(server).branch(C, new AdderS2()); - } catch (ScribbleRuntimeException | IOException | ClassNotFoundException e) { + } catch (ScribRuntimeException | IOException | ClassNotFoundException e) { e.printStackTrace(); } } @@ -54,12 +55,15 @@ public static void main(String[] args) throws Exception { } @Override - public void receive(Adder_S_2 s2, Add op, Buf arg1, Buf arg2) throws ScribbleRuntimeException, IOException, ClassNotFoundException { + 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 ScribbleRuntimeException, IOException { + 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 index f88d3aacd..32dec9fc4 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/FibC1.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/FibC1.java @@ -19,22 +19,23 @@ import static betty16.lec2.adder.Adder.Adder.Adder.Res; import static betty16.lec2.adder.Adder.Adder.Adder.S; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.ObjectStreamFormatter; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Adder_C_1; -import betty16.lec2.adder.Adder.Adder.channels.C.EndSocket; 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.connect(S, SocketChannelEndpoint::new, "localhost", 8888); + 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); @@ -45,7 +46,8 @@ public static void main(String[] args) throws Exception { } // Post: i1.val is the i-th Fibonacci number - private EndSocket fibo(Adder_C_1 c1, Buf i1, Buf i2, int i) throws Exception { + 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 index a7bb10a28..05371bf54 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyAdderC.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyAdderC.java @@ -16,21 +16,22 @@ import static betty16.lec2.adder.Adder.Adder.Adder.C; import static betty16.lec2.adder.Adder.Adder.Adder.S; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.ObjectStreamFormatter; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Adder_C_1; 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.connect(S, SocketChannelEndpoint::new, "localhost", 8888); + try (MPSTEndpoint client = new MPSTEndpoint<>(adder, C, + new ObjectStreamFormatter())) { + client.request(S, SocketChannelEndpoint::new, "localhost", 8888); System.out.println("C: " + new MyAdderC().run(client)); } } diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyAdderS.java b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyAdderS.java index ec9b00e08..2abeacb50 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyAdderS.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyAdderS.java @@ -21,17 +21,17 @@ import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -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 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.channels.S.Adder_S_1; -import betty16.lec2.adder.Adder.Adder.channels.S.Adder_S_1_Cases; 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 { @@ -39,10 +39,11 @@ 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())) { + try (MPSTEndpoint server = new MPSTEndpoint<>(adder, S, + new ObjectStreamFormatter())) { server.accept(ss, C); new MyAdderS().run(new Adder_S_1(server)); - } catch (ScribbleRuntimeException | IOException | ClassNotFoundException e) { + } catch (ScribRuntimeException | IOException | ClassNotFoundException e) { e.printStackTrace(); } } diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyFibC.java b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyFibC.java index beae8888a..6129bc53c 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyFibC.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyFibC.java @@ -16,22 +16,22 @@ import static betty16.lec2.adder.Adder.Adder.Adder.C; import static betty16.lec2.adder.Adder.Adder.Adder.S; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.ObjectStreamFormatter; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Adder_C_1; -import betty16.lec2.adder.Adder.Adder.channels.C.EndSocket; 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.connect(S, SocketChannelEndpoint::new, "localhost", 8888); + client.request(S, SocketChannelEndpoint::new, "localhost", 8888); Buf i1 = new Buf<>(0); Buf i2 = new Buf<>(1); diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/MySmtpC.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/MySmtpC.java index 1ce810ead..3f2f3bb51 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/MySmtpC.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/MySmtpC.java @@ -17,19 +17,19 @@ import static betty16.lec2.smtp.Smtp.Smtp.Smtp.S; import static betty16.lec2.smtp.Smtp.Smtp.Smtp._220; -import org.scribble.runtime.net.scribsock.LinearSocket; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SSLSocketChannelWrapper; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.EndSocket; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_1; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_4; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_6; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.ioifaces.Select_C_S_Ehlo; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.ioifaces.Succ_In_S_250; 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; @@ -40,8 +40,9 @@ public static void main(String[] args) throws Exception { int port = 25; Smtp smtp = new Smtp(); - try (MPSTEndpoint client = new MPSTEndpoint<>(smtp, C, new SmtpMessageFormatter())) { - client.connect(S, SocketChannelEndpoint::new, host, port); + try (MPSTEndpoint client = new MPSTEndpoint<>(smtp, C, + new SmtpMessageFormatter())) { + client.request(S, SocketChannelEndpoint::new, host, port); new MySmtpC().run(new Smtp_C_1(client)); } } diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC1.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC1.java index 21ea4a711..95b941dbb 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC1.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC1.java @@ -19,24 +19,24 @@ import static betty16.lec2.smtp.Smtp.Smtp.Smtp._250; import static betty16.lec2.smtp.Smtp.Smtp.Smtp._250d; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.scribsock.LinearSocket; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SSLSocketChannelWrapper; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.EndSocket; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_1; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_2; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_3; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_3_Cases; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_4; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_6; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_7; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_7_Cases; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_8; 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; @@ -45,12 +45,13 @@ public class SmtpC1 { public static void main(String[] args) throws Exception { - String host = "smtp.cc.ic.ac.uk"; + String host = "...smtp server..."; int port = 25; Smtp smtp = new Smtp(); - try (MPSTEndpoint client = new MPSTEndpoint<>(smtp, C, new SmtpMessageFormatter())) { - client.connect(S, SocketChannelEndpoint::new, host, port); + try (MPSTEndpoint client = new MPSTEndpoint<>(smtp, C, + new SmtpMessageFormatter())) { + client.request(S, SocketChannelEndpoint::new, host, port); new SmtpC1().run(new Smtp_C_1(client)); } } diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC2.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC2.java index 16fd1637e..349a4c652 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC2.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC2.java @@ -19,24 +19,24 @@ import static betty16.lec2.smtp.Smtp.Smtp.Smtp._250; import static betty16.lec2.smtp.Smtp.Smtp.Smtp._250d; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.scribsock.LinearSocket; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SSLSocketChannelWrapper; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.EndSocket; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_1; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.ioifaces.Branch_C_S_250__S_250d; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.ioifaces.Case_C_S_250__S_250d; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.ioifaces.Receive_C_S_220; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.ioifaces.Select_C_S_Ehlo; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.ioifaces.Select_C_S_Quit; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.ioifaces.Select_C_S_StartTls; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.ioifaces.Succ_In_S_220; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.ioifaces.Succ_In_S_250; 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; @@ -45,12 +45,13 @@ public class SmtpC2 { public static void main(String[] args) throws Exception { - String host = "smtp.cc.ic.ac.uk"; + String host = "...smtp server..."; int port = 25; Smtp smtp = new Smtp(); - try (MPSTEndpoint client = new MPSTEndpoint<>(smtp, C, new SmtpMessageFormatter())) { - client.connect(S, SocketChannelEndpoint::new, host, port); + try (MPSTEndpoint client = new MPSTEndpoint<>(smtp, C, + new SmtpMessageFormatter())) { + client.request(S, SocketChannelEndpoint::new, host, port); new SmtpC2().run(new Smtp_C_1(client)); } } diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC3.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC3.java index 3e4b6c825..2d2e31285 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC3.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC3.java @@ -19,22 +19,22 @@ import static betty16.lec2.smtp.Smtp.Smtp.Smtp._250; import static betty16.lec2.smtp.Smtp.Smtp.Smtp._250d; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.scribsock.LinearSocket; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SSLSocketChannelWrapper; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.EndSocket; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_1; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_4; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_6; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.ioifaces.Branch_C_S_250__S_250d; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.ioifaces.Case_C_S_250__S_250d; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.ioifaces.Select_C_S_Ehlo; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.ioifaces.Succ_In_S_250; 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; @@ -43,12 +43,13 @@ public class SmtpC3 { public static void main(String[] args) throws Exception { - String host = "smtp.cc.ic.ac.uk"; + String host = "...smtp server..."; int port = 25; Smtp smtp = new Smtp(); - try (MPSTEndpoint client = new MPSTEndpoint<>(smtp, C, new SmtpMessageFormatter())) { - client.connect(S, SocketChannelEndpoint::new, host, port); + try (MPSTEndpoint client = new MPSTEndpoint<>(smtp, C, + new SmtpMessageFormatter())) { + client.request(S, SocketChannelEndpoint::new, host, port); new SmtpC3().run(new Smtp_C_1(client)); } } diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC4.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC4.java index 239400b09..617cfa93d 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC4.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC4.java @@ -18,22 +18,22 @@ import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.scribsock.LinearSocket; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SSLSocketChannelWrapper; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Smtp_C_1; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_3; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_3_Handler; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_4; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_7; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_7_Handler; -import betty16.lec2.smtp.Smtp.Smtp.channels.C.Smtp_C_8; 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; @@ -45,13 +45,14 @@ public class SmtpC4 { public static void main(String[] args) throws Exception { - String host = "smtp.cc.ic.ac.uk"; + String host = "...smtp server..."; int port = 25; Smtp smtp = new Smtp(); - try (MPSTEndpoint client = new MPSTEndpoint<>(smtp, Smtp.C, new SmtpMessageFormatter())) + try (MPSTEndpoint client = new MPSTEndpoint<>(smtp, Smtp.C, + new SmtpMessageFormatter())) { - client.connect(S, SocketChannelEndpoint::new, host, port); + client.request(S, SocketChannelEndpoint::new, host, port); new SmtpC4().run(new Smtp_C_1(client)); } } @@ -67,7 +68,7 @@ private void run(Smtp_C_1 c1) throws Exception { 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 ScribbleRuntimeException, IOException, ClassNotFoundException + 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()); @@ -75,7 +76,7 @@ public void receive(Smtp_C_3 s3, betty16.lec2.smtp.Smtp.Smtp.ops._250d op, Buf<_ } @Override - public void receive(Smtp_C_4 s4, betty16.lec2.smtp.Smtp.Smtp.ops._250 op, Buf<_250> arg) throws ScribbleRuntimeException, IOException, ClassNotFoundException + 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()); @@ -89,7 +90,7 @@ public void receive(Smtp_C_4 s4, betty16.lec2.smtp.Smtp.Smtp.ops._250 op, Buf<_2 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 ScribbleRuntimeException, IOException, ClassNotFoundException + 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()); @@ -97,7 +98,7 @@ public void receive(Smtp_C_7 s7, betty16.lec2.smtp.Smtp.Smtp.ops._250d op, Buf<_ } @Override - public void receive(Smtp_C_8 s8, betty16.lec2.smtp.Smtp.Smtp.ops._250 op, Buf<_250> arg) throws ScribbleRuntimeException, IOException, ClassNotFoundException + 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()); 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 index c45a3873c..b2c5f5b81 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/SmtpMessage.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/SmtpMessage.java @@ -13,8 +13,8 @@ */ package betty16.lec2.smtp.message; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.type.name.Op; +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; 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 index 83edfb65f..9540ae25e 100644 --- a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/SmtpMessageFormatter.java +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/SmtpMessageFormatter.java @@ -19,8 +19,8 @@ import java.nio.ByteBuffer; import java.nio.charset.Charset; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.runtime.net.ScribMessageFormatter; +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; diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLongC.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLongC.java index 06b76dce3..33b06b8e5 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLongC.java +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLongC.java @@ -30,18 +30,18 @@ import static bettybook.http.longv.HttpLong.Http.Http._200; import static bettybook.http.longv.HttpLong.Http.Http._404; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.EndSocket; -import bettybook.http.longv.HttpLong.Http.channels.C.Http_C_1; -import bettybook.http.longv.HttpLong.Http.channels.C.Http_C_3; -import bettybook.http.longv.HttpLong.Http.channels.C.Http_C_4_Cases; -import bettybook.http.longv.HttpLong.Http.channels.C.Http_C_5; -import bettybook.http.longv.HttpLong.Http.channels.C.Http_C_5_Cases; 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; @@ -51,21 +51,22 @@ 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 = "www.doc.ic.ac.uk"; int port = 80; - //String host = "localhost"; int port = 8080; + 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.connect(S, SocketChannelEndpoint::new, host, port); - new HttpLongC().run(new Http_C_1(client), host); + 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) throws Exception { - doResponse(doRequest(s1, host)); + 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) throws Exception { - return s1.send(S, new RequestLine("/~rhu/", "1.1")) + 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("")); } diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLongS.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLongS.java index bad1e886f..5fd4ceefa 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLongS.java +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLongS.java @@ -28,17 +28,17 @@ import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.scribsock.ScribServerSocket; -import org.scribble.runtime.net.scribsock.SocketChannelServer; -import org.scribble.runtime.net.session.MPSTEndpoint; +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.channels.S.Http_S_1; -import bettybook.http.longv.HttpLong.Http.channels.S.Http_S_2; -import bettybook.http.longv.HttpLong.Http.channels.S.Http_S_2_Cases; 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; @@ -52,12 +52,13 @@ 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())) { + try (MPSTEndpoint server = new MPSTEndpoint<>(http, S, + new HttpLongMessageFormatter())) { server.accept(ss, C); run(new Http_S_1(server)); } - catch (IOException | ClassNotFoundException | ScribbleRuntimeException e) + catch (IOException | ClassNotFoundException | ScribRuntimeException e) { e.printStackTrace(); } @@ -65,7 +66,8 @@ public static void main(String[] args) throws Exception } } - private static void run(Http_S_1 s1) throws ClassNotFoundException, ScribbleRuntimeException, IOException { + 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); 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 index f16fdd3a7..9ea724145 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/HeaderField.java +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/HeaderField.java @@ -13,7 +13,7 @@ */ package bettybook.http.longv.message; -import org.scribble.sesstype.name.Op; +import org.scribble.core.type.name.Op; public abstract class HeaderField extends HttpLongMessage { 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 index ce00a3b3c..7b4cce573 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/HttpLongMessage.java +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/HttpLongMessage.java @@ -13,8 +13,8 @@ */ package bettybook.http.longv.message; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.sesstype.name.Op; +import org.scribble.core.type.name.Op; +import org.scribble.runtime.message.ScribMessage; import bettybook.http.longv.HttpLong.Http.Http; 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 index 300bc30be..2ff68850c 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/HttpLongMessageFormatter.java +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/HttpLongMessageFormatter.java @@ -19,8 +19,8 @@ import java.nio.ByteBuffer; import java.nio.charset.Charset; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.runtime.net.ScribMessageFormatter; +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; @@ -192,7 +192,11 @@ else if (front.equals(HttpLongMessage.HTTP)) 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); + default: { + //throw new RuntimeException("Cannot parse header field: " + line); + System.err.println("Cannot parse header field, attempting to skip: " + line); + return fromBytes(bb); + } } } else 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 index 976806fd5..ac7122583 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/StartLine.java +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/StartLine.java @@ -13,7 +13,7 @@ */ package bettybook.http.longv.message; -import org.scribble.sesstype.name.Op; +import org.scribble.core.type.name.Op; public abstract class StartLine extends HttpLongMessage { 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 index ca6c1d29a..f2216df9e 100644 --- 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 @@ -13,7 +13,7 @@ */ package bettybook.http.longv.message.server; -import org.scribble.sesstype.name.Op; +import org.scribble.core.type.name.Op; import bettybook.http.longv.message.HttpLongMessage; diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShort.scr b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShort.scr index 2a9d856b6..e8baa5d33 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShort.scr +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShort.scr @@ -1,7 +1,7 @@ /** * Assuming scribblec.sh in scribble-java root directory: * - * ./scribblec.sh -d scribble-demos/scrib/bettybook/src scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShort.scr -api Http C + * bin/scribblec.sh -d scribble-demos/scrib/bettybook/src scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShort.scr -api Http 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 index 81154027b..c0c12b183 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShortC.java +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShortC.java @@ -17,37 +17,40 @@ import static bettybook.http.shortv.HttpShort.Http.Http.Resp; import static bettybook.http.shortv.HttpShort.Http.Http.S; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Http_C_1; 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 { + public static void main(String[] args) throws Exception + { Http http = new Http(); - try (MPSTEndpoint client = new MPSTEndpoint<>(http, C, new HttpShortMessageFormatter())) { - String host = "www.doc.ic.ac.uk"; int port = 80; - //String host = "summerschool2016.behavioural-types.eu"; int port = 80; - //String host = "localhost"; int port = 8080; - - client.connect(S, SocketChannelEndpoint::new, host, port); - new HttpShortC().run(client, host); + 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) throws Exception { + 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("/~rhu/", "1.1", host)) + c.send(S, new Req(file, "1.1", host)) .receive(S, Resp, buf); diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShortS.java b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShortS.java index 16b46384d..0ff18c669 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShortS.java +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShortS.java @@ -19,32 +19,36 @@ import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.scribsock.ScribServerSocket; -import org.scribble.runtime.net.scribsock.SocketChannelServer; -import org.scribble.runtime.net.session.MPSTEndpoint; +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.channels.S.Http_S_1; -import bettybook.http.shortv.HttpShort.Http.channels.S.Http_S_2; 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) { + 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())) { + try (MPSTEndpoint server = new MPSTEndpoint<>(http, S, + new HttpShortMessageFormatter())) { server.accept(ss, C); run(new Http_S_1(server)); } - catch (IOException | ClassNotFoundException | ScribbleRuntimeException e) + catch (IOException | ClassNotFoundException | ScribRuntimeException e) { e.printStackTrace(); } @@ -52,7 +56,9 @@ public static void main(String[] args) throws IOException { } } - private static void run(Http_S_1 s1) throws ClassNotFoundException, ScribbleRuntimeException, IOException { + 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); 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 index 23a17ad6e..e31d5e111 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/message/HttpShortMessage.java +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/message/HttpShortMessage.java @@ -13,8 +13,8 @@ */ package bettybook.http.shortv.message; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.sesstype.name.Op; +import org.scribble.core.type.name.Op; +import org.scribble.runtime.message.ScribMessage; import bettybook.http.shortv.HttpShort.Http.Http; 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 index 7cb02a27e..4964fe91f 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/message/HttpShortMessageFormatter.java +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/message/HttpShortMessageFormatter.java @@ -20,8 +20,8 @@ import java.nio.charset.Charset; import java.util.Arrays; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.runtime.net.ScribMessageFormatter; +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; @@ -149,7 +149,10 @@ private static HttpShortMessage parseRequest(String msg) 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)); + 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); } diff --git a/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMathC.java b/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMathC.java index 91f2e4f7f..bc3e50dac 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMathC.java +++ b/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMathC.java @@ -11,10 +11,14 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -//$ java -cp modules/core/target/classes/ -Djava.security.policy=file:/C:/cygwin/home/Raymond/code/scribble/github-rhu1/scribble-java/modules/demos/scrib/bettybook/src/bettybook/math/rmi/server.policy bettybook.math.rmi.RMIMathC + +//$ 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; @@ -22,9 +26,6 @@ public class RMIMathC { public static void main(String[] args) throws Exception { - //System.setProperty("java.security.policy", "file:/C:/cygwin/home/Raymond/code/scribble/github-rhu1/scribble-java/modules/demos/scrib/bettybook/src/bettybook/math/rmi/server.policy"); - //if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } - Registry registry = LocateRegistry.getRegistry(8888); RMIMath mathS = (RMIMath) registry.lookup("MathService"); diff --git a/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMathS.java b/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMathS.java index 3b4b59b4b..0c674cd2c 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMathS.java +++ b/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMathS.java @@ -11,8 +11,9 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -//$ java -cp modules/core/target/classes/ -Djava.security.policy=file:/C:/cygwin/home/Raymond/code/scribble/github-rhu1/scribble-java/modules/demos/scrib/bettybook/src/bettybook/math/rmi/server.policy bettybook.math.rmi.RMIMathS -//$ java -cp modules/core/target/classes/ -Djava.rmi.server.codebase=file:/C:/cygwin/home/Raymond/code/scribble/github-rhu1/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 -- codebase arg not working + +//$ 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; @@ -60,8 +61,8 @@ public static void main(String[] args) throws Exception - //System.setProperty("java.security.policy","file:/C:/cygwin64/home/rhu/code/eclipse/scribble/github.com/rhu1/scribble-java/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/server.policy"); + //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.rmi.server.codebase=file:/C:\cygwin64\home\rhu\code\eclipse\scribble\github.com\rhu1\scribble-java\scribble-demos\bettybook\target\classes/ + /*-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/scrib/Math.scr b/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/Math.scr index c45966aff..f63c2a817 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/Math.scr +++ b/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/Math.scr @@ -4,7 +4,7 @@ module bettybook.math.scrib.Math; -type "java.lang.Integer" from "rt.jar" as Int; +data "java.lang.Integer" from "rt.jar" as Int; // N.B. calling this Math will clash with java.lang.Math diff --git a/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathC.java b/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathC.java index 9c009052d..872078e5e 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathC.java +++ b/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathC.java @@ -22,15 +22,15 @@ import static bettybook.math.scrib.Math.MathService.MathService.Sum; import static bettybook.math.scrib.Math.MathService.MathService.Val; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.ObjectStreamFormatter; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.EndSocket; -import bettybook.math.scrib.Math.MathService.channels.C.MathService_C_1; 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 { @@ -44,9 +44,9 @@ 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.connect(S, SocketChannelEndpoint::new, "localhost", 8888); + 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); @@ -86,7 +86,7 @@ private int fibo(int i) throws Exception MathService sess = new MathService(); try (MPSTEndpoint se = new MPSTEndpoint<>(sess, C, new ObjectStreamFormatter())) { - se.connect(S, SocketChannelEndpoint::new, "localhost", 8888); + se.request(S, SocketChannelEndpoint::new, "localhost", 8888); fibo(new MathService_C_1(se), i1, i2, new Buf<>(i)); diff --git a/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathS1.java b/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathS1.java index 04ca384ac..eabcd55b8 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathS1.java +++ b/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathS1.java @@ -22,17 +22,17 @@ import static bettybook.math.scrib.Math.MathService.MathService.Sum; import static bettybook.math.scrib.Math.MathService.MathService.Val; -import org.scribble.runtime.net.Buf; -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 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.channels.S.MathService_S_1; -import bettybook.math.scrib.Math.MathService.channels.S.MathService_S_1_Cases; -import bettybook.math.scrib.Math.MathService.channels.S.MathService_S_2_Cases; 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 { @@ -48,8 +48,8 @@ private void run() throws Exception while (true) { MathService sess = new MathService(); - try (MPSTEndpoint se = new MPSTEndpoint<>(sess, S, new ObjectStreamFormatter())) - { + try (MPSTEndpoint se = new MPSTEndpoint<>(sess, S, + new ObjectStreamFormatter())) { se.accept(ss, C); Buf b1 = new Buf<>(); Buf b2 = new Buf<>(); diff --git a/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathS2.java b/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathS2.java index 896c7efba..f670c01e1 100644 --- a/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathS2.java +++ b/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathS2.java @@ -20,26 +20,26 @@ import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -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 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.channels.S.EndSocket; -import bettybook.math.scrib.Math.MathService.channels.S.MathService_S_1; -import bettybook.math.scrib.Math.MathService.channels.S.MathService_S_1_Handler; -import bettybook.math.scrib.Math.MathService.channels.S.MathService_S_2; -import bettybook.math.scrib.Math.MathService.channels.S.MathService_S_2_Handler; -import bettybook.math.scrib.Math.MathService.channels.S.MathService_S_3; -import bettybook.math.scrib.Math.MathService.channels.S.MathService_S_4; 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 { @@ -50,8 +50,8 @@ public static void main(String[] args) throws Exception while (true) { MathService sess = new MathService(); - try (MPSTEndpoint se = new MPSTEndpoint<>(sess, S, new ObjectStreamFormatter())) - { + try (MPSTEndpoint se = new MPSTEndpoint<>(sess, S, + new ObjectStreamFormatter())) { se.accept(ss, C); MathService_S_1 s1 = new MathService_S_1(se); @@ -69,14 +69,14 @@ class MathSHandler implements MathService_S_1_Handler, MathService_S_2_Handler @Override public void receive(MathService_S_2 s2, Val op, Buf b1) - throws ScribbleRuntimeException, IOException, ClassNotFoundException + throws ScribRuntimeException, IOException, ClassNotFoundException { this.b1 = b1; s2.branch(C, this); } @Override - public void receive(EndSocket end, Bye op) throws ScribbleRuntimeException, + public void receive(EndSocket end, Bye op) throws ScribRuntimeException, IOException, ClassNotFoundException { @@ -84,14 +84,14 @@ public void receive(EndSocket end, Bye op) throws ScribbleRuntimeException, @Override public void receive(MathService_S_3 s3, Add op, Buf b2) - throws ScribbleRuntimeException, IOException, ClassNotFoundException + 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 ScribbleRuntimeException, IOException, ClassNotFoundException + throws ScribRuntimeException, IOException, ClassNotFoundException { s4.send(C, Prod, this.b1.val * b2.val).branch(C, this); } diff --git a/scribble-demos/scrib/coco/src/coco/fibo/Fibo.scr b/scribble-demos/scrib/coco/src/coco/fibo/Fibo.scr index 28a35f3a0..9786773ee 100644 --- a/scribble-demos/scrib/coco/src/coco/fibo/Fibo.scr +++ b/scribble-demos/scrib/coco/src/coco/fibo/Fibo.scr @@ -4,7 +4,7 @@ module coco.fibo.Fibo; -type "java.lang.Long" from "rt.jar" as Long; +data "java.lang.Long" from "rt.jar" as Long; global protocol Fibonacci(role A, role B) diff --git a/scribble-demos/scrib/coco/src/coco/fibo/FiboA.java b/scribble-demos/scrib/coco/src/coco/fibo/FiboA.java index 693710fef..27fd0338c 100644 --- a/scribble-demos/scrib/coco/src/coco/fibo/FiboA.java +++ b/scribble-demos/scrib/coco/src/coco/fibo/FiboA.java @@ -18,20 +18,20 @@ import static coco.fibo.Fibo.Fibonacci.Fibonacci.fibonacci; import static coco.fibo.Fibo.Fibonacci.Fibonacci.stop; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.ObjectStreamFormatter; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.A.EndSocket; -import coco.fibo.Fibo.Fibonacci.channels.A.Fibonacci_A_1; -import coco.fibo.Fibo.Fibonacci.channels.A.ioifaces.In_B_fibonacci_Long; -import coco.fibo.Fibo.Fibonacci.channels.A.ioifaces.Out_B_fibonacci_Long; -import coco.fibo.Fibo.Fibonacci.channels.A.ioifaces.Out_B_stop; -import coco.fibo.Fibo.Fibonacci.channels.A.ioifaces.Succ_In_B_fibonacci_Long; -import coco.fibo.Fibo.Fibonacci.channels.A.ioifaces.Succ_Out_B_fibonacci_Long; 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 { @@ -47,9 +47,10 @@ public FiboA(Fibonacci fib) public void run() { int n = 19; - try (MPSTEndpoint se = new MPSTEndpoint<>(this.fib, A, new ObjectStreamFormatter())) + try (MPSTEndpoint se = new MPSTEndpoint<>(this.fib, A, + new ObjectStreamFormatter())) { - se.connect(B, SocketChannelEndpoint::new, "localhost", 8888); + se.request(B, SocketChannelEndpoint::new, "localhost", 8888); run(new Fibonacci_A_1(se), n); // 4184 System.out.println("A #" + n + ": " + this.b.val); } diff --git a/scribble-demos/scrib/coco/src/coco/fibo/FiboB.java b/scribble-demos/scrib/coco/src/coco/fibo/FiboB.java index 7d46ae065..139d9b216 100644 --- a/scribble-demos/scrib/coco/src/coco/fibo/FiboB.java +++ b/scribble-demos/scrib/coco/src/coco/fibo/FiboB.java @@ -18,17 +18,17 @@ import static coco.fibo.Fibo.Fibonacci.Fibonacci.fibonacci; import static coco.fibo.Fibo.Fibonacci.Fibonacci.stop; -import org.scribble.runtime.net.Buf; -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 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.channels.B.EndSocket; -import coco.fibo.Fibo.Fibonacci.channels.B.Fibonacci_B_1; -import coco.fibo.Fibo.Fibonacci.channels.B.Fibonacci_B_1_Cases; 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 { @@ -45,7 +45,8 @@ public void run() { try ( ScribServerSocket ss = new SocketChannelServer(8888); - MPSTEndpoint se = new MPSTEndpoint<>(this.fib, B, new ObjectStreamFormatter())) + MPSTEndpoint se = new MPSTEndpoint<>(this.fib, B, + new ObjectStreamFormatter())) { se.accept(ss, A); run(new Fibonacci_B_1(se)); diff --git a/scribble-demos/scrib/coco/src/coco/fibo/FiboBHandler.java b/scribble-demos/scrib/coco/src/coco/fibo/FiboBHandler.java index 242a65222..c46a00027 100644 --- a/scribble-demos/scrib/coco/src/coco/fibo/FiboBHandler.java +++ b/scribble-demos/scrib/coco/src/coco/fibo/FiboBHandler.java @@ -19,21 +19,21 @@ import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -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 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.channels.B.EndSocket; -import coco.fibo.Fibo.Fibonacci.channels.B.Fibonacci_B_1; -import coco.fibo.Fibo.Fibonacci.channels.B.Fibonacci_B_1_Handler; -import coco.fibo.Fibo.Fibonacci.channels.B.Fibonacci_B_2; 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 { @@ -50,7 +50,8 @@ public void run() { try ( ScribServerSocket ss = new SocketChannelServer(8888); - MPSTEndpoint se = new MPSTEndpoint<>(this.fib, B, new ObjectStreamFormatter())) + MPSTEndpoint se = new MPSTEndpoint<>(this.fib, B, + new ObjectStreamFormatter())) { se.accept(ss, A); new Fibonacci_B_1(se).branch(A, this); @@ -64,13 +65,15 @@ public void run() } /*/ @Override - public void receive(Fibonacci_B_2 s2, fibonacci op, Buf arg1) throws ScribbleRuntimeException, IOException, ClassNotFoundException + 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 ScribbleRuntimeException, IOException, ClassNotFoundException + 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/smtp/MySmtpC.java b/scribble-demos/scrib/coco/src/coco/smtp/MySmtpC.java index 9462f1d53..8039da897 100644 --- a/scribble-demos/scrib/coco/src/coco/smtp/MySmtpC.java +++ b/scribble-demos/scrib/coco/src/coco/smtp/MySmtpC.java @@ -19,21 +19,21 @@ import static coco.smtp.Smtp.Smtp.Smtp.S; import static coco.smtp.Smtp.Smtp.Smtp._220; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.scribsock.LinearSocket; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SSLSocketChannelWrapper; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Smtp_C_1; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Out_S_Ehlo; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Receive_C_S_220; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Select_C_S_Ehlo; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Select_C_S_Quit; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Select_C_S_StartTls; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Succ_In_S_250; 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; @@ -56,9 +56,9 @@ public void run() throws Exception int port = 25; Smtp smtp = new Smtp(); - try (MPSTEndpoint se = new MPSTEndpoint<>(smtp, C, new SmtpMessageFormatter())) - { - se.connect(S, SocketChannelEndpoint::new, host, port); + 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( diff --git a/scribble-demos/scrib/coco/src/coco/smtp/SmtpC1.java b/scribble-demos/scrib/coco/src/coco/smtp/SmtpC1.java index c416dccf4..6ef39d541 100644 --- a/scribble-demos/scrib/coco/src/coco/smtp/SmtpC1.java +++ b/scribble-demos/scrib/coco/src/coco/smtp/SmtpC1.java @@ -22,23 +22,23 @@ import static coco.smtp.Smtp.Smtp.Smtp._250; import static coco.smtp.Smtp.Smtp.Smtp._250d; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.scribsock.LinearSocket; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SSLSocketChannelWrapper; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Smtp_C_1; -import coco.smtp.Smtp.Smtp.channels.C.Smtp_C_2; -import coco.smtp.Smtp.Smtp.channels.C.Smtp_C_3; -import coco.smtp.Smtp.Smtp.channels.C.Smtp_C_3_Cases; -import coco.smtp.Smtp.Smtp.channels.C.Smtp_C_4; -import coco.smtp.Smtp.Smtp.channels.C.Smtp_C_6; -import coco.smtp.Smtp.Smtp.channels.C.Smtp_C_7; -import coco.smtp.Smtp.Smtp.channels.C.Smtp_C_7_Cases; -import coco.smtp.Smtp.Smtp.channels.C.Smtp_C_8; 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; @@ -60,13 +60,13 @@ public static void main(String[] args) throws Exception public void run() throws Exception { - String host = "smtp.cc.ic.ac.uk"; + String host = "...smtp server..."; int port = 25; Smtp smtp = new Smtp(); - try (MPSTEndpoint se = new MPSTEndpoint<>(smtp, C, new SmtpMessageFormatter())) - { - se.connect(S, SocketChannelEndpoint::new, host, port); + 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( diff --git a/scribble-demos/scrib/coco/src/coco/smtp/SmtpC2.java b/scribble-demos/scrib/coco/src/coco/smtp/SmtpC2.java index 250b8c2c8..ceb0727e0 100644 --- a/scribble-demos/scrib/coco/src/coco/smtp/SmtpC2.java +++ b/scribble-demos/scrib/coco/src/coco/smtp/SmtpC2.java @@ -21,23 +21,23 @@ import static coco.smtp.Smtp.Smtp.Smtp._250; import static coco.smtp.Smtp.Smtp.Smtp._250d; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.scribsock.LinearSocket; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SSLSocketChannelWrapper; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Smtp_C_1; -import coco.smtp.Smtp.Smtp.channels.C.Smtp_C_1_Future; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Branch_C_S_250__S_250d; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Case_C_S_250__S_250d; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Receive_C_S_220; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Select_C_S_Ehlo; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Select_C_S_Quit; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Select_C_S_StartTls; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Succ_In_S_250; 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; @@ -59,13 +59,13 @@ public static void main(String[] args) throws Exception public void run() throws Exception { - String host = "smtp.cc.ic.ac.uk"; + String host = "...smtp server..."; int port = 25; Smtp smtp = new Smtp(); - try (MPSTEndpoint se = new MPSTEndpoint<>(smtp, Smtp.C, new SmtpMessageFormatter())) - { - se.connect(Smtp.S, SocketChannelEndpoint::new, host, port); + 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); diff --git a/scribble-demos/scrib/coco/src/coco/smtp/SmtpC3.java b/scribble-demos/scrib/coco/src/coco/smtp/SmtpC3.java index d30a08724..5fb4d44ce 100644 --- a/scribble-demos/scrib/coco/src/coco/smtp/SmtpC3.java +++ b/scribble-demos/scrib/coco/src/coco/smtp/SmtpC3.java @@ -22,20 +22,20 @@ import static coco.smtp.Smtp.Smtp.Smtp._250; import static coco.smtp.Smtp.Smtp.Smtp._250d; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.scribsock.LinearSocket; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SSLSocketChannelWrapper; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Smtp_C_1; -import coco.smtp.Smtp.Smtp.channels.C.Smtp_C_1_Future; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Branch_C_S_250__S_250d; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Case_C_S_250__S_250d; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Select_C_S_Ehlo; -import coco.smtp.Smtp.Smtp.channels.C.ioifaces.Succ_In_S_250; 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; @@ -58,13 +58,13 @@ public static void main(String[] args) throws Exception public void run() throws Exception { - String host = "smtp.cc.ic.ac.uk"; + String host = "...smtp server..."; int port = 25; Smtp smtp = new Smtp(); try (MPSTEndpoint se = new MPSTEndpoint<>(smtp, C, new SmtpMessageFormatter())) { - se.connect(S, SocketChannelEndpoint::new, host, port); + se.request(S, SocketChannelEndpoint::new, host, port); Smtp_C_1 s1 = new Smtp_C_1(se); Buf b = new Buf<>(); diff --git a/scribble-demos/scrib/coco/src/coco/smtp/message/SmtpMessage.java b/scribble-demos/scrib/coco/src/coco/smtp/message/SmtpMessage.java index ea5c7dc74..ff7499bd9 100644 --- a/scribble-demos/scrib/coco/src/coco/smtp/message/SmtpMessage.java +++ b/scribble-demos/scrib/coco/src/coco/smtp/message/SmtpMessage.java @@ -13,8 +13,8 @@ */ package coco.smtp.message; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.sesstype.name.Op; +import org.scribble.core.type.name.Op; +import org.scribble.runtime.message.ScribMessage; import org.scribble.util.Caller; import coco.smtp.Smtp.Smtp.Smtp; diff --git a/scribble-demos/scrib/coco/src/coco/smtp/message/SmtpMessageFormatter.java b/scribble-demos/scrib/coco/src/coco/smtp/message/SmtpMessageFormatter.java index fb2fb7045..cd010038f 100644 --- a/scribble-demos/scrib/coco/src/coco/smtp/message/SmtpMessageFormatter.java +++ b/scribble-demos/scrib/coco/src/coco/smtp/message/SmtpMessageFormatter.java @@ -19,8 +19,8 @@ import java.nio.ByteBuffer; import java.nio.charset.Charset; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.runtime.net.ScribMessageFormatter; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; import coco.smtp.message.server._220; import coco.smtp.message.server._250; diff --git a/scribble-demos/scrib/fase16/src/fase16/adder/Adder.scr b/scribble-demos/scrib/fase16/src/fase16/adder/Adder.scr index ef521fdeb..2abbcbe52 100644 --- a/scribble-demos/scrib/fase16/src/fase16/adder/Adder.scr +++ b/scribble-demos/scrib/fase16/src/fase16/adder/Adder.scr @@ -5,7 +5,7 @@ module fase16.adder.Adder; -type "java.lang.Integer" from "rt.jar" as Integer; +data "java.lang.Integer" from "rt.jar" as Integer; global protocol Adder(role C, role S) diff --git a/scribble-demos/scrib/fase16/src/fase16/adder/AdderC.java b/scribble-demos/scrib/fase16/src/fase16/adder/AdderC.java index 8d09c8f7a..7bf12f0d1 100644 --- a/scribble-demos/scrib/fase16/src/fase16/adder/AdderC.java +++ b/scribble-demos/scrib/fase16/src/fase16/adder/AdderC.java @@ -19,15 +19,15 @@ import static fase16.adder.Adder.Adder.Adder.Res; import static fase16.adder.Adder.Adder.Adder.S; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.ObjectStreamFormatter; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Adder_C_1; -import fase16.adder.Adder.Adder.channels.C.Adder_C_3; 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 { @@ -42,9 +42,9 @@ public static void main(String[] args) throws Exception private static void adder() throws Exception { Adder adder = new Adder(); - try (MPSTEndpoint se = new MPSTEndpoint<>(adder, C, new ObjectStreamFormatter())) - { - se.connect(S, SocketChannelEndpoint::new, "localhost", 8888); + 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); @@ -79,7 +79,7 @@ private static void fib() throws Exception Adder adder = new Adder(); try (MPSTEndpoint se = new MPSTEndpoint<>(adder, C, new ObjectStreamFormatter())) { - se.connect(S, SocketChannelEndpoint::new, "localhost", 8888); + se.request(S, SocketChannelEndpoint::new, "localhost", 8888); Adder_C_1 s1 = new Adder_C_1(se); Buf i = new Buf<>(0); diff --git a/scribble-demos/scrib/fase16/src/fase16/adder/AdderS.java b/scribble-demos/scrib/fase16/src/fase16/adder/AdderS.java index 0267090d9..5ba75ebb3 100644 --- a/scribble-demos/scrib/fase16/src/fase16/adder/AdderS.java +++ b/scribble-demos/scrib/fase16/src/fase16/adder/AdderS.java @@ -21,18 +21,18 @@ import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -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 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.channels.S.Adder_S_1; -import fase16.adder.Adder.Adder.channels.S.Adder_S_1_Cases; -import fase16.adder.Adder.Adder.channels.S.Adder_S_3; 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 @@ -47,13 +47,13 @@ public static void main(String[] args) throws Exception while (true) { Adder adder = new Adder(); - try (MPSTEndpoint se = new MPSTEndpoint<>(adder, S, new ObjectStreamFormatter())) - { + 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 (ScribbleRuntimeException | IOException | ClassNotFoundException e) + catch (ScribRuntimeException | IOException | ClassNotFoundException e) { e.printStackTrace(); } diff --git a/scribble-demos/scrib/fase16/src/fase16/adder/MyAdderC.java b/scribble-demos/scrib/fase16/src/fase16/adder/MyAdderC.java index da117410b..2e413a086 100644 --- a/scribble-demos/scrib/fase16/src/fase16/adder/MyAdderC.java +++ b/scribble-demos/scrib/fase16/src/fase16/adder/MyAdderC.java @@ -13,26 +13,31 @@ */ package fase16.adder; -import static fase16.adder.Adder.Adder.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.net.Buf; -import org.scribble.runtime.net.ObjectStreamFormatter; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Adder_C_1; -import fase16.adder.Adder.Adder.channels.C.Adder_C_2; -import fase16.adder.Adder.Adder.channels.C.Adder_C_3; 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.connect(S, SocketChannelEndpoint::new, "localhost", 8888); + try (MPSTEndpoint se = new MPSTEndpoint<>(adder, C, + new ObjectStreamFormatter())) + { + se.request(S, SocketChannelEndpoint::new, "localhost", 8888); Buf i = new Buf<>(); @@ -50,7 +55,8 @@ public static void main(String[] args) throws Exception private static final int N = 10; - private static Adder_C_3 fib(Adder_C_1 s1, Buf i1, Buf i2, int i) throws Exception + 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/SmtpC.java b/scribble-demos/scrib/fase16/src/fase16/smtp/SmtpC.java index b0b190d02..49b1ecbf9 100644 --- a/scribble-demos/scrib/fase16/src/fase16/smtp/SmtpC.java +++ b/scribble-demos/scrib/fase16/src/fase16/smtp/SmtpC.java @@ -25,24 +25,24 @@ import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.scribsock.LinearSocket; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SSLSocketChannelWrapper; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Smtp_C_1; -import fase16.smtp.Smtp.Smtp.channels.C.Smtp_C_1_Future; -import fase16.smtp.Smtp.Smtp.channels.C.Smtp_C_3; -import fase16.smtp.Smtp.Smtp.channels.C.Smtp_C_3_Handler; -import fase16.smtp.Smtp.Smtp.channels.C.Smtp_C_4; -import fase16.smtp.Smtp.Smtp.channels.C.ioifaces.Branch_C_S_250__S_250d; -import fase16.smtp.Smtp.Smtp.channels.C.ioifaces.Case_C_S_250__S_250d; -import fase16.smtp.Smtp.Smtp.channels.C.ioifaces.Select_C_S_Ehlo; -import fase16.smtp.Smtp.Smtp.channels.C.ioifaces.Succ_In_S_250; 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; @@ -68,9 +68,10 @@ public void run() throws Exception int port = 25; Smtp smtp = new Smtp(); - try (MPSTEndpoint se = new MPSTEndpoint<>(smtp, Smtp.C, new SmtpMessageFormatter())) + try (MPSTEndpoint se = new MPSTEndpoint<>(smtp, Smtp.C, + new SmtpMessageFormatter())) { - se.connect(Smtp.S, SocketChannelEndpoint::new, host, port); + se.request(Smtp.S, SocketChannelEndpoint::new, host, port); Buf f1 = new Buf<>(); Smtp_C_1 s1 = new Smtp_C_1(se); @@ -157,13 +158,17 @@ public static > S printlnBuf(S s, B b) 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 ScribbleRuntimeException, IOException, ClassNotFoundException + 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 ScribbleRuntimeException, IOException, ClassNotFoundException + public void receive(Smtp_C_4 s4, fase16.smtp.Smtp.Smtp.ops._250 op, + Buf<_250> arg) + throws ScribRuntimeException, IOException, ClassNotFoundException { try { @@ -175,13 +180,13 @@ public void receive(Smtp_C_4 s4, fase16.smtp.Smtp.Smtp.ops._250 op, Buf<_250> ar ) .send(S, new Quit()); } - catch (ScribbleRuntimeException | IOException | ClassNotFoundException x) + catch (ScribRuntimeException | IOException | ClassNotFoundException x) { throw x; } catch (Exception x) { - throw new ScribbleRuntimeException(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 index d48c9cb8f..621094a83 100644 --- a/scribble-demos/scrib/fase16/src/fase16/smtp/message/SmtpMessage.java +++ b/scribble-demos/scrib/fase16/src/fase16/smtp/message/SmtpMessage.java @@ -13,8 +13,8 @@ */ package fase16.smtp.message; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.sesstype.name.Op; +import org.scribble.core.type.name.Op; +import org.scribble.runtime.message.ScribMessage; import org.scribble.util.Caller; import fase16.smtp.Smtp.Smtp.Smtp; diff --git a/scribble-demos/scrib/fase16/src/fase16/smtp/message/SmtpMessageFormatter.java b/scribble-demos/scrib/fase16/src/fase16/smtp/message/SmtpMessageFormatter.java index 731f1780f..fcb8f4771 100644 --- a/scribble-demos/scrib/fase16/src/fase16/smtp/message/SmtpMessageFormatter.java +++ b/scribble-demos/scrib/fase16/src/fase16/smtp/message/SmtpMessageFormatter.java @@ -19,8 +19,8 @@ import java.nio.ByteBuffer; import java.nio.charset.Charset; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.runtime.net.ScribMessageFormatter; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; import fase16.smtp.message.server._220; import fase16.smtp.message.server._250; @@ -48,7 +48,8 @@ public byte[] toBytes(ScribMessage m) throws IOException } @Override - public ScribMessage fromBytes(ByteBuffer bb) throws IOException, ClassNotFoundException + public ScribMessage fromBytes(ByteBuffer bb) + throws IOException, ClassNotFoundException { bb.flip(); //byte[] bs = new byte[2]; diff --git a/scribble-demos/scrib/fib/src/fib/AdderClient.java b/scribble-demos/scrib/fib/src/fib/AdderClient.java index 568c62d56..5350e50e5 100644 --- a/scribble-demos/scrib/fib/src/fib/AdderClient.java +++ b/scribble-demos/scrib/fib/src/fib/AdderClient.java @@ -20,32 +20,35 @@ import java.net.UnknownHostException; import java.util.concurrent.ExecutionException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.ObjectStreamFormatter; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Adder_C_1; -import fib.Fib.Adder.channels.C.ioifaces.Receive_C_S_BYE; -import fib.Fib.Adder.channels.C.ioifaces.Receive_C_S_RES_Int; -import fib.Fib.Adder.channels.C.ioifaces.Select_C_S_ADD_Int_Int__S_BYE; -import fib.Fib.Adder.channels.C.ioifaces.Succ_Out_S_BYE; 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, ScribbleRuntimeException, IOException, ClassNotFoundException, ExecutionException, InterruptedException + 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())) + try (MPSTEndpoint se = new MPSTEndpoint<>(adder, Adder.C, + new ObjectStreamFormatter())) { - se.connect(Adder.S, SocketChannelEndpoint::new, "localhost", 8888); + se.request(Adder.S, SocketChannelEndpoint::new, "localhost", 8888); Adder_C_1 s1 = new Adder_C_1(se); @@ -72,8 +75,8 @@ public static void main(String[] args) throws UnknownHostException, ScribbleRunt } } - private static Succ_Out_S_BYE foo(Select_C_S_ADD_Int_Int__S_BYE s, Buf i) throws ClassNotFoundException, ScribbleRuntimeException, IOException - //private static EndSocket foo(Select_C_S_ADD_Integer_Integer__S_BYE s, Buf i) throws ClassNotFoundException, ScribbleRuntimeException, IOException + 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( @@ -85,7 +88,7 @@ private static Succ_Out_S_BYE foo(Select_C_S_ADD_Int_Int__S_BYE s, Buf fib(Buf i1, Buf i2, Adder_C_1 s1) throws ScribbleRuntimeException, IOException, ClassNotFoundException, ExecutionException, InterruptedException + /*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, diff --git a/scribble-demos/scrib/fib/src/fib/AdderServer.java b/scribble-demos/scrib/fib/src/fib/AdderServer.java index 98af66c80..5465ae60a 100644 --- a/scribble-demos/scrib/fib/src/fib/AdderServer.java +++ b/scribble-demos/scrib/fib/src/fib/AdderServer.java @@ -16,22 +16,23 @@ import java.io.IOException; import java.util.concurrent.ExecutionException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -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 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.channels.S.Adder_S_1; -import fib.Fib.Adder.channels.S.Adder_S_1_Cases; -import fib.Fib.Adder.channels.S.Adder_S_3; 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, ScribbleRuntimeException, ExecutionException, InterruptedException + public static void main(String[] args) throws IOException, + ScribRuntimeException, ExecutionException, InterruptedException { try (ScribServerSocket ss = new SocketChannelServer(8888)) { @@ -41,13 +42,14 @@ public static void main(String[] args) throws IOException, ScribbleRuntimeExcept while (true) { Adder foo = new Adder(); - try (MPSTEndpoint se = new MPSTEndpoint<>(foo, Adder.S, new ObjectStreamFormatter())) + 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 (ScribbleRuntimeException | IOException | ClassNotFoundException e) + catch (ScribRuntimeException | IOException | ClassNotFoundException e) { e.printStackTrace(); } @@ -55,7 +57,9 @@ public static void main(String[] args) throws IOException, ScribbleRuntimeExcept } } - private static Adder_S_3 X(Adder_S_1 s1, Buf i1, Buf i2) throws ClassNotFoundException, ScribbleRuntimeException, IOException, ExecutionException, InterruptedException + 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) diff --git a/scribble-demos/scrib/fib/src/fib/Fib.scr b/scribble-demos/scrib/fib/src/fib/Fib.scr index ff927b38f..3a2be9408 100644 --- a/scribble-demos/scrib/fib/src/fib/Fib.scr +++ b/scribble-demos/scrib/fib/src/fib/Fib.scr @@ -4,7 +4,7 @@ module fib.Fib; -type "java.lang.Integer" from "rt.jar" as Int; +data "java.lang.Integer" from "rt.jar" as Int; global protocol Adder(role C, role S) diff --git a/scribble-demos/scrib/fib/src/fib/FibClient.java b/scribble-demos/scrib/fib/src/fib/FibClient.java index 1cca32012..69c929601 100644 --- a/scribble-demos/scrib/fib/src/fib/FibClient.java +++ b/scribble-demos/scrib/fib/src/fib/FibClient.java @@ -17,29 +17,32 @@ import java.net.UnknownHostException; import java.util.concurrent.ExecutionException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.ObjectStreamFormatter; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Adder_C_1; -import fib.Fib.Adder.channels.C.Adder_C_2; -import fib.Fib.Adder.channels.C.Adder_C_3; 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, ScribbleRuntimeException, IOException, ClassNotFoundException, ExecutionException, InterruptedException + 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())) + try (MPSTEndpoint se = new MPSTEndpoint<>(adder, Adder.C, + new ObjectStreamFormatter())) { - se.connect(Adder.S, SocketChannelEndpoint::new, "localhost", 8888); + se.request(Adder.S, SocketChannelEndpoint::new, "localhost", 8888); Adder_C_1 s1 = new Adder_C_1(se); @@ -47,7 +50,9 @@ public static void main(String[] args) throws UnknownHostException, ScribbleRunt } } - private static Adder_C_3 fib(Adder_C_1 s1, Buf i1, Buf i2, int i) throws ClassNotFoundException, ScribbleRuntimeException, IOException, ExecutionException, InterruptedException + 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) diff --git a/scribble-demos/scrib/fib/src/fib/Fibo.java b/scribble-demos/scrib/fib/src/fib/Fibo.java index ef65b5870..acf74a8b2 100644 --- a/scribble-demos/scrib/fib/src/fib/Fibo.java +++ b/scribble-demos/scrib/fib/src/fib/Fibo.java @@ -17,24 +17,24 @@ import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -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 org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.A.Fibonacci_A_1; -import fib.Fib.Fibonacci.channels.B.EndSocket; -import fib.Fib.Fibonacci.channels.B.Fibonacci_B_1; -import fib.Fib.Fibonacci.channels.B.Fibonacci_B_1_Handler; -import fib.Fib.Fibonacci.channels.B.Fibonacci_B_2; 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 { @@ -59,9 +59,9 @@ public MyB(Fibonacci fib) @Override public void run() { - try ( - ScribServerSocket ss = new SocketChannelServer(8888); - MPSTEndpoint se = new MPSTEndpoint<>(this.fib, Fibonacci.B, new ObjectStreamFormatter())) + 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); @@ -73,13 +73,15 @@ public void run() } @Override - public void receive(Fibonacci_B_2 s, fibonacci op, Buf arg1) throws ScribbleRuntimeException, IOException, ClassNotFoundException + 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 ScribbleRuntimeException, IOException, ClassNotFoundException + public void receive(EndSocket schan, end op) + throws ScribRuntimeException, IOException, ClassNotFoundException { //System.out.println("B done: " + this.x); } @@ -98,9 +100,10 @@ public MyA(Fibonacci fib) @Override public void run() { - try (MPSTEndpoint se = new MPSTEndpoint<>(this.fib, Fibonacci.A, new ObjectStreamFormatter())) + try (MPSTEndpoint se = new MPSTEndpoint<>(this.fib, + Fibonacci.A, new ObjectStreamFormatter())) { - se.connect(Fibonacci.B, SocketChannelEndpoint::new, "localhost", 8888); + se.request(Fibonacci.B, SocketChannelEndpoint::new, "localhost", 8888); run(new Fibonacci_A_1(se), 19); // 4184 System.out.println("A done: " + this.b.val); } @@ -110,7 +113,8 @@ public void run() } } - private fib.Fib.Fibonacci.channels.A.EndSocket run(Fibonacci_A_1 s, int todo) throws Exception + private fib.Fib.Fibonacci.statechans.A.EndSocket run(Fibonacci_A_1 s, int todo) + throws Exception { return (todo > 0) ? run( diff --git a/scribble-demos/scrib/fib/src/fib/MyAdderC.java b/scribble-demos/scrib/fib/src/fib/MyAdderC.java index 1e3943e10..2755ae8ea 100644 --- a/scribble-demos/scrib/fib/src/fib/MyAdderC.java +++ b/scribble-demos/scrib/fib/src/fib/MyAdderC.java @@ -13,22 +13,23 @@ */ package fib; -import org.scribble.runtime.net.ObjectStreamFormatter; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Adder_C_1; 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())) + try (MPSTEndpoint se = new MPSTEndpoint<>(adder, Adder.C, + new ObjectStreamFormatter())) { - se.connect(Adder.S, SocketChannelEndpoint::new, "localhost", 8888); + se.request(Adder.S, SocketChannelEndpoint::new, "localhost", 8888); Adder_C_1 s1 = new Adder_C_1(se); diff --git a/scribble-demos/scrib/http/src/http/longvers/HttpLongC.java b/scribble-demos/scrib/http/src/http/longvers/HttpLongC.java index df6ebe762..683ad2d54 100644 --- a/scribble-demos/scrib/http/src/http/longvers/HttpLongC.java +++ b/scribble-demos/scrib/http/src/http/longvers/HttpLongC.java @@ -30,19 +30,19 @@ import static http.longvers.HttpLong.Http.Http._200; import static http.longvers.HttpLong.Http.Http._404; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Http_C_1; -import http.longvers.HttpLong.Http.channels.C.Http_C_3; -import http.longvers.HttpLong.Http.channels.C.Http_C_4_Cases; -import http.longvers.HttpLong.Http.channels.C.Http_C_5; -import http.longvers.HttpLong.Http.channels.C.Http_C_5_Cases; -import http.longvers.HttpLong.Http.channels.C.ioifaces.Branch_C_S_200__S_404.Branch_C_S_200__S_404_Enum; 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; @@ -52,6 +52,13 @@ 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 @@ -67,22 +74,23 @@ public static void main(String[] args) throws Exception public void run() throws Exception { Http http = new Http(); - try (MPSTEndpoint client = new MPSTEndpoint<>(http, C, new HttpLongMessageFormatter())) - { - String host = "www.doc.ic.ac.uk"; int port = 80; - //String host = "localhost"; int port = 8080; + 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.connect(S, SocketChannelEndpoint::new, host, port); + client.request(S, SocketChannelEndpoint::new, host, port); doResponse( - doRequest(new Http_C_1(client), host) + doRequest(new Http_C_1(client), host, file) ); } } - private Http_C_3 doRequest(Http_C_1 s1, String host) throws Exception + private Http_C_3 doRequest(Http_C_1 s1, String host, String file) throws Exception { - return s1.send(S, new RequestLine("/~rhu/", "1.1")) + return s1.send(S, new RequestLine(file, "1.1")) .send(S, new Host(host)) .send(S, new Body("")); } @@ -138,7 +146,7 @@ public void run1() throws Exception String host = "www.doc.ic.ac.uk"; int port = 80; //String host = "localhost"; int port = 8080; - se.connect(S, SocketChannelEndpoint::new, host, port); + se.request(S, SocketChannelEndpoint::new, host, port); Http_C_1 s1 = new Http_C_1(se); diff --git a/scribble-demos/scrib/http/src/http/longvers/HttpLongS.java b/scribble-demos/scrib/http/src/http/longvers/HttpLongS.java index 3667964d8..375d8c8cf 100644 --- a/scribble-demos/scrib/http/src/http/longvers/HttpLongS.java +++ b/scribble-demos/scrib/http/src/http/longvers/HttpLongS.java @@ -13,16 +13,16 @@ */ package http.longvers; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.scribsock.ScribServerSocket; -import org.scribble.runtime.net.scribsock.SocketChannelServer; -import org.scribble.runtime.net.session.MPSTEndpoint; +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.channels.S.Http_S_1; -import http.longvers.HttpLong.Http.channels.S.Http_S_2; -import http.longvers.HttpLong.Http.channels.S.Http_S_2_Cases; 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; diff --git a/scribble-demos/scrib/http/src/http/longvers/message/HeaderField.java b/scribble-demos/scrib/http/src/http/longvers/message/HeaderField.java index f3b3e856c..0c6774462 100644 --- a/scribble-demos/scrib/http/src/http/longvers/message/HeaderField.java +++ b/scribble-demos/scrib/http/src/http/longvers/message/HeaderField.java @@ -13,7 +13,7 @@ */ package http.longvers.message; -import org.scribble.type.name.Op; +import org.scribble.core.type.name.Op; public abstract class HeaderField extends HttpLongMessage { diff --git a/scribble-demos/scrib/http/src/http/longvers/message/HttpLongMessage.java b/scribble-demos/scrib/http/src/http/longvers/message/HttpLongMessage.java index edad3cf62..2dea67fc9 100644 --- a/scribble-demos/scrib/http/src/http/longvers/message/HttpLongMessage.java +++ b/scribble-demos/scrib/http/src/http/longvers/message/HttpLongMessage.java @@ -13,8 +13,8 @@ */ package http.longvers.message; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.type.name.Op; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.core.type.name.Op; import http.longvers.HttpLong.Http.Http; diff --git a/scribble-demos/scrib/http/src/http/longvers/message/HttpLongMessageFormatter.java b/scribble-demos/scrib/http/src/http/longvers/message/HttpLongMessageFormatter.java index 02f1eb7df..6c4ecdb98 100644 --- a/scribble-demos/scrib/http/src/http/longvers/message/HttpLongMessageFormatter.java +++ b/scribble-demos/scrib/http/src/http/longvers/message/HttpLongMessageFormatter.java @@ -19,8 +19,8 @@ import java.nio.ByteBuffer; import java.nio.charset.Charset; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.runtime.net.ScribMessageFormatter; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; import http.longvers.message.client.Accept; import http.longvers.message.client.AcceptEncoding; @@ -195,7 +195,11 @@ else if (front.equals(HttpLongMessage.HTTP)) 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); + default: { + //throw new RuntimeException("Cannot parse header field: " + line); + System.err.println("Cannot parse header field, attempting to skip: " + line); + return fromBytes(bb); + } } } else diff --git a/scribble-demos/scrib/http/src/http/longvers/message/StartLine.java b/scribble-demos/scrib/http/src/http/longvers/message/StartLine.java index 99e62c280..54d86be69 100644 --- a/scribble-demos/scrib/http/src/http/longvers/message/StartLine.java +++ b/scribble-demos/scrib/http/src/http/longvers/message/StartLine.java @@ -13,7 +13,7 @@ */ package http.longvers.message; -import org.scribble.type.name.Op; +import org.scribble.core.type.name.Op; public abstract class StartLine extends HttpLongMessage { 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 index 82f04a166..730d707cf 100644 --- a/scribble-demos/scrib/http/src/http/longvers/message/server/StatusCode.java +++ b/scribble-demos/scrib/http/src/http/longvers/message/server/StatusCode.java @@ -13,7 +13,7 @@ */ package http.longvers.message.server; -import org.scribble.type.name.Op; +import org.scribble.core.type.name.Op; import http.longvers.message.HttpLongMessage; diff --git a/scribble-demos/scrib/http/src/http/shortvers/HttpShort.scr b/scribble-demos/scrib/http/src/http/shortvers/HttpShort.scr index e3c186862..42de41bc9 100644 --- a/scribble-demos/scrib/http/src/http/shortvers/HttpShort.scr +++ b/scribble-demos/scrib/http/src/http/shortvers/HttpShort.scr @@ -1,5 +1,5 @@ //$ ./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.longvers.HttpShort.Http -d scribble-demos/scrib/http/javadoc/shortvers +//$ 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; diff --git a/scribble-demos/scrib/http/src/http/shortvers/HttpShortC.java b/scribble-demos/scrib/http/src/http/shortvers/HttpShortC.java index 66056f347..d863860e1 100644 --- a/scribble-demos/scrib/http/src/http/shortvers/HttpShortC.java +++ b/scribble-demos/scrib/http/src/http/shortvers/HttpShortC.java @@ -17,12 +17,12 @@ import static http.shortvers.HttpShort.Http.Http.RESPONSE; import static http.shortvers.HttpShort.Http.Http.S; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Http_C_1; +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; @@ -45,14 +45,14 @@ public void run() throws Exception Http http = new Http(); try (MPSTEndpoint client = new MPSTEndpoint<>(http, C, new HttpShortMessageFormatter())) { - String host = "www.doc.ic.ac.uk"; int port = 80; - //String host = "localhost"; int port = 8080; - - client.connect(S, SocketChannelEndpoint::new, host, port); + 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("/~rhu/", "1.1", host)) + .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 index 7734305d4..03161daf1 100644 --- a/scribble-demos/scrib/http/src/http/shortvers/HttpShortS.java +++ b/scribble-demos/scrib/http/src/http/shortvers/HttpShortS.java @@ -19,21 +19,20 @@ import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.scribsock.ScribServerSocket; -import org.scribble.runtime.net.scribsock.SocketChannelServer; -import org.scribble.runtime.net.session.MPSTEndpoint; +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.channels.S.Http_S_1; -import http.shortvers.HttpShort.Http.channels.S.Http_S_2; 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; -// FIXME: (Firefox) Cannot parse header field: Cookie: __utma=111872281.1372348290.1498163262.1498163262.1498163262.1; __utmz=111872281.1498163262.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) public class HttpShortS { public HttpShortS() @@ -48,7 +47,8 @@ public static void main(String[] args) throws IOException while (true) { Http http = new Http(); - try (MPSTEndpoint se = new MPSTEndpoint<>(http, S, new HttpShortMessageFormatter())) + try (MPSTEndpoint se = new MPSTEndpoint<>(http, S, + new HttpShortMessageFormatter())) { se.accept(ss, C); @@ -59,7 +59,7 @@ public static void main(String[] args) throws IOException s2.send(C, new Response("1.1", "Hello")); } - catch (IOException | ClassNotFoundException | ScribbleRuntimeException e) + 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 index d6124ab35..7c452ff0f 100644 --- a/scribble-demos/scrib/http/src/http/shortvers/message/HttpShortMessage.java +++ b/scribble-demos/scrib/http/src/http/shortvers/message/HttpShortMessage.java @@ -13,8 +13,8 @@ */ package http.shortvers.message; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.type.name.Op; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.core.type.name.Op; import http.shortvers.HttpShort.Http.Http; diff --git a/scribble-demos/scrib/http/src/http/shortvers/message/HttpShortMessageFormatter.java b/scribble-demos/scrib/http/src/http/shortvers/message/HttpShortMessageFormatter.java index 17bf3b872..fe1898a5c 100644 --- a/scribble-demos/scrib/http/src/http/shortvers/message/HttpShortMessageFormatter.java +++ b/scribble-demos/scrib/http/src/http/shortvers/message/HttpShortMessageFormatter.java @@ -20,8 +20,8 @@ import java.nio.charset.Charset; import java.util.Arrays; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.runtime.net.ScribMessageFormatter; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; import http.shortvers.message.client.Request; import http.shortvers.message.server.Response; @@ -151,7 +151,10 @@ private static HttpShortMessage parseRequest(String msg) 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)); + 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); } diff --git a/scribble-demos/scrib/loan/src/loan/LoanApplicant.java b/scribble-demos/scrib/loan/src/loan/LoanApplicant.java index 449298442..39d3b0df9 100644 --- a/scribble-demos/scrib/loan/src/loan/LoanApplicant.java +++ b/scribble-demos/scrib/loan/src/loan/LoanApplicant.java @@ -19,15 +19,15 @@ import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.reject; import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.requestConfirmation; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.ObjectStreamFormatter; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.Applicant.BuyerBrokerSupplier_Applicant_1; -import loan.LoanApplication.BuyerBrokerSupplier.channels.Applicant.BuyerBrokerSupplier_Applicant_2_Cases; 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 { @@ -37,7 +37,7 @@ public static void main(String[] args) throws Exception try (MPSTEndpoint se = new MPSTEndpoint<>(sess, Applicant, new ObjectStreamFormatter())) { - se.connect(ApplicationPortal, SocketChannelEndpoint::new, "localhost", 8888); + se.request(ApplicationPortal, SocketChannelEndpoint::new, "localhost", 8888); BuyerBrokerSupplier_Applicant_2_Cases branch = new BuyerBrokerSupplier_Applicant_1(se) diff --git a/scribble-demos/scrib/loan/src/loan/LoanApplication.scr b/scribble-demos/scrib/loan/src/loan/LoanApplication.scr index 4cbcb5360..b6beab53c 100644 --- a/scribble-demos/scrib/loan/src/loan/LoanApplication.scr +++ b/scribble-demos/scrib/loan/src/loan/LoanApplication.scr @@ -1,18 +1,18 @@ -//$ bin/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 +//$ ./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; -/*type "CustomerName" from "CustomerName.xsd" as CustomerName; -type "DateOfBirth" from "DateOfBirth.xsd" as DateOfBirth; -type "AnnualSalary" from "AnnualSalary.xsd" as AnnualSalary; -type "CreditRating" from "CreditRating.xsd" as CreditRating; -type "LoanAmount" from "LoanAmount.xsd" as LoanAmount; -type "Approval" from "Approval.xsd" as Approval;*/ +/*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;*/ -type "java.lang.Integer" from "rt.jar" as Int; -type "java.lang.String" from "rt.jar" as String; -type "java.lang.Boolean" from "rt.jar" as Bool; +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) { diff --git a/scribble-demos/scrib/loan/src/loan/LoanApplicationPortal.java b/scribble-demos/scrib/loan/src/loan/LoanApplicationPortal.java index 863c96a03..0091a12bc 100644 --- a/scribble-demos/scrib/loan/src/loan/LoanApplicationPortal.java +++ b/scribble-demos/scrib/loan/src/loan/LoanApplicationPortal.java @@ -25,17 +25,17 @@ import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.respond; import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.sendLoanAmount; -import org.scribble.runtime.net.Buf; -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 org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.ApplicationPortal.BuyerBrokerSupplier_ApplicationPortal_1; -import loan.LoanApplication.BuyerBrokerSupplier.channels.ApplicationPortal.BuyerBrokerSupplier_ApplicationPortal_4; 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 { @@ -45,11 +45,12 @@ public static void main(String[] args) throws Exception try ( ScribServerSocket ss = new SocketChannelServer(8888); MPSTEndpoint se - = new MPSTEndpoint<>(sess, ApplicationPortal, new ObjectStreamFormatter())) + = new MPSTEndpoint<>(sess, ApplicationPortal, + new ObjectStreamFormatter())) { se.accept(ss, Applicant); - se.connect(ProcessingDept, SocketChannelEndpoint::new, "localhost", 7777); - se.connect(FinanceDept, SocketChannelEndpoint::new, "localhost", 9999); + se.request(ProcessingDept, SocketChannelEndpoint::new, "localhost", 7777); + se.request(FinanceDept, SocketChannelEndpoint::new, "localhost", 9999); Buf customerName = new Buf<>(); Buf dateOfBirth = new Buf<>(); @@ -58,10 +59,11 @@ public static void main(String[] args) throws Exception 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); + .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<>(); diff --git a/scribble-demos/scrib/loan/src/loan/LoanFinanceDept.java b/scribble-demos/scrib/loan/src/loan/LoanFinanceDept.java index e3f7a0807..ef5aae496 100644 --- a/scribble-demos/scrib/loan/src/loan/LoanFinanceDept.java +++ b/scribble-demos/scrib/loan/src/loan/LoanFinanceDept.java @@ -19,16 +19,16 @@ import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.reject; import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.sendLoanAmount; -import org.scribble.runtime.net.Buf; -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 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.channels.FinanceDept.BuyerBrokerSupplier_FinanceDept_1; -import loan.LoanApplication.BuyerBrokerSupplier.channels.FinanceDept.BuyerBrokerSupplier_FinanceDept_1_Cases; 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 { diff --git a/scribble-demos/scrib/loan/src/loan/LoanProcessingDept.java b/scribble-demos/scrib/loan/src/loan/LoanProcessingDept.java index 2455f8eb1..800b613cc 100644 --- a/scribble-demos/scrib/loan/src/loan/LoanProcessingDept.java +++ b/scribble-demos/scrib/loan/src/loan/LoanProcessingDept.java @@ -18,15 +18,15 @@ import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.checkEligibility; import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.respond; -import org.scribble.runtime.net.Buf; -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 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.channels.ProcessingDept.BuyerBrokerSupplier_ProcessingDept_1; import loan.LoanApplication.BuyerBrokerSupplier.roles.ProcessingDept; +import loan.LoanApplication.BuyerBrokerSupplier.statechans.ProcessingDept.BuyerBrokerSupplier_ProcessingDept_1; public class LoanProcessingDept { @@ -36,7 +36,8 @@ public static void main(String[] args) throws Exception try ( ScribServerSocket ss = new SocketChannelServer(7777); MPSTEndpoint se - = new MPSTEndpoint<>(sess, ProcessingDept, new ObjectStreamFormatter())) + = new MPSTEndpoint<>(sess, ProcessingDept, + new ObjectStreamFormatter())) { se.accept(ss, ApplicationPortal); @@ -45,8 +46,9 @@ public static void main(String[] args) throws Exception Buf annualSalary = new Buf<>(); Buf creditRating = new Buf<>(); new BuyerBrokerSupplier_ProcessingDept_1(se) - .receive(ApplicationPortal, checkEligibility, customerName, dateOfBirth, annualSalary, creditRating) - .send(ApplicationPortal, respond, true); + .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 index 847cd3631..081ac337c 100644 --- a/scribble-demos/scrib/nego/src/nego/Nego1.scr +++ b/scribble-demos/scrib/nego/src/nego/Nego1.scr @@ -2,7 +2,7 @@ module nego.Nego1; -type "test.nego.SAP" from "test/nego/SAP.java" as SAP; +data "test.nego.SAP" from "test/nego/SAP.java" as SAP; // C = Consumer, P = Producer global protocol Negotiate(role C, role P) diff --git a/scribble-demos/scrib/nego/src/nego/Nego2.scr b/scribble-demos/scrib/nego/src/nego/Nego2.scr index 17231c7de..132f1c3a8 100644 --- a/scribble-demos/scrib/nego/src/nego/Nego2.scr +++ b/scribble-demos/scrib/nego/src/nego/Nego2.scr @@ -2,7 +2,7 @@ module demo.nego.Nego2; -type "test.nego.SAP" from "test/nego/SAP.java" as SAP; +data "test.nego.SAP" from "test/nego/SAP.java" as SAP; // C = Consumer, P = Producer global protocol Negotiate(role C, role P) diff --git a/scribble-demos/scrib/nego/src/nego/Nego3.scr b/scribble-demos/scrib/nego/src/nego/Nego3.scr index 6a3f5d705..83e3e65d8 100644 --- a/scribble-demos/scrib/nego/src/nego/Nego3.scr +++ b/scribble-demos/scrib/nego/src/nego/Nego3.scr @@ -2,7 +2,7 @@ module demo.nego.Nego3; -type "test.nego.SAP" from "test/nego/SAP.java" as SAP; +data "test.nego.SAP" from "test/nego/SAP.java" as SAP; // C = Consumer, P = Producer global protocol Negotiate(role C, role P) diff --git a/scribble-demos/scrib/smtp/src/smtp/SimpleSmtpC.java b/scribble-demos/scrib/smtp/src/smtp/SimpleSmtpC.java index 763817c04..8fb895f42 100644 --- a/scribble-demos/scrib/smtp/src/smtp/SimpleSmtpC.java +++ b/scribble-demos/scrib/smtp/src/smtp/SimpleSmtpC.java @@ -11,7 +11,8 @@ * 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/demos/target/classes smtp.SimpleSmtpC + +//$ java -cp scribble-runtime/target/classes/:scribble-core/target/classes:scribble-demos/target/classes smtp.SimpleSmtpC package smtp; @@ -19,6 +20,7 @@ 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; @@ -31,24 +33,24 @@ import java.io.InputStreamReader; import java.util.Base64; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.scribsock.LinearSocket; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SSLSocketChannelWrapper; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Smtp_C_1; -import smtp.Smtp.Smtp.channels.C.Smtp_C_10; -import smtp.Smtp.Smtp.channels.C.Smtp_C_11_Cases; -import smtp.Smtp.Smtp.channels.C.Smtp_C_4; -import smtp.Smtp.Smtp.channels.C.Smtp_C_6; -import smtp.Smtp.Smtp.channels.C.Smtp_C_8; -import smtp.Smtp.Smtp.channels.C.Smtp_C_9_Cases; -import smtp.Smtp.Smtp.channels.C.ioifaces.Branch_C_S_250__S_250d; -import smtp.Smtp.Smtp.channels.C.ioifaces.Case_C_S_250__S_250d; -import smtp.Smtp.Smtp.channels.C.ioifaces.Select_C_S_Ehlo; -import smtp.Smtp.Smtp.channels.C.ioifaces.Succ_In_S_250; +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; @@ -76,15 +78,15 @@ public void run() throws Exception int port = 25; String ehlo = "user.testing.com"; - String mail = "rhu@doc.ic.ac.uk"; // Sender - String rcpt = mail; + 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.connect(S, SocketChannelEndpoint::new, host, port); + se.request(S, SocketChannelEndpoint::new, host, port); Smtp_C_11_Cases cases = doAuth( @@ -93,25 +95,25 @@ public void run() throws Exception doEhlo(new Smtp_C_1(se).async(S, _220), ehlo) ) , ehlo)) - .send(S, new Mail(mail)) + .send(S, new Mail(mailFrom)) .branch(S); switch (cases.getOp()) { case _250: { cases.receive(_250) - .send(S, new Rcpt(rcpt)).async(S, _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()); + .send(S, new Quit()).async(S, _221); break; } case _501: { - cases.receive(_501).send(S, new Quit()); + cases.receive(_501).send(S, new Quit()).async(S, _221); } } } diff --git a/scribble-demos/scrib/smtp/src/smtp/SmtpC.java b/scribble-demos/scrib/smtp/src/smtp/SmtpC.java index 5da6df415..ff4b1c098 100644 --- a/scribble-demos/scrib/smtp/src/smtp/SmtpC.java +++ b/scribble-demos/scrib/smtp/src/smtp/SmtpC.java @@ -12,8 +12,7 @@ * the License. */ - -//$ java -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/target/classes smtp.SmtpC smtp.cc.ic.ac.uk foo@foo.com bar@bar.com subj body +//$ 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; @@ -34,25 +33,26 @@ import java.io.InputStreamReader; import java.util.Base64; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SSLSocketChannelWrapper; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Smtp_C_1; -import smtp.Smtp.Smtp.channels.C.Smtp_C_10; -import smtp.Smtp.Smtp.channels.C.Smtp_C_11_Cases; -import smtp.Smtp.Smtp.channels.C.Smtp_C_12; -import smtp.Smtp.Smtp.channels.C.Smtp_C_2; -import smtp.Smtp.Smtp.channels.C.Smtp_C_3; -import smtp.Smtp.Smtp.channels.C.Smtp_C_3_Cases; -import smtp.Smtp.Smtp.channels.C.Smtp_C_4; -import smtp.Smtp.Smtp.channels.C.Smtp_C_6; -import smtp.Smtp.Smtp.channels.C.Smtp_C_7; -import smtp.Smtp.Smtp.channels.C.Smtp_C_7_Cases; -import smtp.Smtp.Smtp.channels.C.Smtp_C_8; -import smtp.Smtp.Smtp.channels.C.Smtp_C_9_Cases; +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; @@ -71,16 +71,16 @@ public class SmtpC private static final int PORT = 25; private final String server; // e.g., smtp.cc.ic.ac.uk; - private final String mailTo; // foo@foo.com - private final String rcptFrom; // bar@bar.com + 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 mailTo, String rcptFrom, String subj, String body) throws Exception + public SmtpC(String server, String mailFrom, String rcptTo, String subj, String body) throws Exception { this.server = server; - this.mailTo = mailTo; - this.rcptFrom = rcptFrom; + this.mailFrom = mailFrom; + this.rcptTo = rcptTo; this.subj = subj; this.body = body; @@ -98,7 +98,7 @@ public void run() throws Exception try (MPSTEndpoint se = new MPSTEndpoint<>(smtp, C, new SmtpMessageFormatter())) { - se.connect(S, SocketChannelEndpoint::new, this.server, SmtpC.PORT); + 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<>()); @@ -111,7 +111,7 @@ public void run() throws Exception ))); Smtp_C_11_Cases s11cases = - s10.send(S, new Mail(this.mailTo)) + s10.send(S, new Mail(this.mailFrom)) .branch(S); switch (s11cases.op) { @@ -213,18 +213,19 @@ private Smtp_C_10 doAuth(Smtp_C_8 s8) throws Exception } } - private void sendMail(Smtp_C_12 s12) throws Exception + private EndSocket sendMail(Smtp_C_12 s12) throws Exception { - s12.send(S, new Rcpt(this.rcptFrom)) - .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<>()); + 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<>()); } diff --git a/scribble-demos/scrib/smtp/src/smtp/message/SmtpMessage.java b/scribble-demos/scrib/smtp/src/smtp/message/SmtpMessage.java index a2a037cba..e3860c471 100644 --- a/scribble-demos/scrib/smtp/src/smtp/message/SmtpMessage.java +++ b/scribble-demos/scrib/smtp/src/smtp/message/SmtpMessage.java @@ -13,8 +13,8 @@ */ package smtp.message; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.sesstype.name.Op; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.core.type.name.Op; import org.scribble.util.Caller; import smtp.Smtp.Smtp.Smtp; diff --git a/scribble-demos/scrib/smtp/src/smtp/message/SmtpMessageFormatter.java b/scribble-demos/scrib/smtp/src/smtp/message/SmtpMessageFormatter.java index 6195d77a5..c28f36091 100644 --- a/scribble-demos/scrib/smtp/src/smtp/message/SmtpMessageFormatter.java +++ b/scribble-demos/scrib/smtp/src/smtp/message/SmtpMessageFormatter.java @@ -19,8 +19,8 @@ import java.nio.ByteBuffer; import java.nio.charset.Charset; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.runtime.net.ScribMessageFormatter; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; import smtp.message.server._220; import smtp.message.server._221; @@ -275,6 +275,7 @@ private void readMinimumBytes(DataInputStream dis, int min) throws IOException } }*/ + @Deprecated @Override public void writeMessage(DataOutputStream dos, ScribMessage m) throws IOException { @@ -282,6 +283,7 @@ public void writeMessage(DataOutputStream dos, ScribMessage m) throws IOExceptio dos.flush(); } + @Deprecated @Override public SmtpMessage readMessage(DataInputStream dis) throws IOException { diff --git a/scribble-demos/scrib/threebuyer/src/threebuyer/ThreeBuyer.scr b/scribble-demos/scrib/threebuyer/src/threebuyer/ThreeBuyer.scr index d3ce0b25c..6e691d748 100644 --- a/scribble-demos/scrib/threebuyer/src/threebuyer/ThreeBuyer.scr +++ b/scribble-demos/scrib/threebuyer/src/threebuyer/ThreeBuyer.scr @@ -5,9 +5,9 @@ module threebuyer.ThreeBuyer; -type "java.lang.Integer" from "rt.jar" as Int; -type "java.lang.String" from "rt.jar" as String; -type "test.twobuyer.Date" from "test/twobuyer/Date.java" as Date; +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 diff --git a/scribble-demos/scrib/threebuyer/src/threebuyer/ThreeBuyer2.scr b/scribble-demos/scrib/threebuyer/src/threebuyer/ThreeBuyer2.scr index e70dc5284..ab1eef33f 100644 --- a/scribble-demos/scrib/threebuyer/src/threebuyer/ThreeBuyer2.scr +++ b/scribble-demos/scrib/threebuyer/src/threebuyer/ThreeBuyer2.scr @@ -1,9 +1,9 @@ module threebuyer.ThreeBuyer2; -type "java.lang.Integer" from "rt.jar" as Int; -type "java.lang.String" from "rt.jar" as String; -type "test.twobuyer.Date" from "test/twobuyer/Date.java" as Date; +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 diff --git a/scribble-demos/scrib/travel/src/travel/BookingA.java b/scribble-demos/scrib/travel/src/travel/BookingA.java index 0dc3a931d..26391c76b 100644 --- a/scribble-demos/scrib/travel/src/travel/BookingA.java +++ b/scribble-demos/scrib/travel/src/travel/BookingA.java @@ -16,21 +16,22 @@ import java.io.IOException; import java.util.concurrent.ExecutionException; -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 org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.A.Booking_A_1; -import travel.Travel.Booking.channels.A.Booking_A_1_Cases; 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, ScribbleRuntimeException, ExecutionException, InterruptedException + public static void main(String[] args) throws IOException, + ScribRuntimeException, ExecutionException, InterruptedException { try (ScribServerSocket ss_C = new SocketChannelServer(7777)) { @@ -39,13 +40,14 @@ public static void main(String[] args) throws IOException, ScribbleRuntimeExcept int quote = 1000; Booking booking = new Booking(); - try (MPSTEndpoint se = new MPSTEndpoint<>(booking, Booking.A, new ObjectStreamFormatter())) + try (MPSTEndpoint se = new MPSTEndpoint<>(booking, + Booking.A, new ObjectStreamFormatter())) { se.accept(ss_C, Booking.C); - //Thread.sleep(1000); // FIXME: ensure S is ready + //Thread.sleep(1000); // CHECKME: ensure S is ready - se.connect(Booking.S, SocketChannelEndpoint::new, "localhost", 9999); + se.request(Booking.S, SocketChannelEndpoint::new, "localhost", 9999); Booking_A_1 s1 = new Booking_A_1(se); Booking_A_1_Cases s1cases; diff --git a/scribble-demos/scrib/travel/src/travel/BookingC.java b/scribble-demos/scrib/travel/src/travel/BookingC.java index 3c4e09d76..b9574c376 100644 --- a/scribble-demos/scrib/travel/src/travel/BookingC.java +++ b/scribble-demos/scrib/travel/src/travel/BookingC.java @@ -17,29 +17,32 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.ObjectStreamFormatter; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Booking_C_1; -import travel.Travel.Booking.channels.C.Booking_C_5; 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()); + 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())) + try (MPSTEndpoint se = new MPSTEndpoint<>(booking, Booking.C, + new ObjectStreamFormatter())) { - se.connect(Booking.A, SocketChannelEndpoint::new, "localhost", 7777); - se.connect(Booking.S, SocketChannelEndpoint::new, "localhost", 8888); + 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<>(); diff --git a/scribble-demos/scrib/travel/src/travel/BookingS.java b/scribble-demos/scrib/travel/src/travel/BookingS.java index 2606a1dc6..6d59298fa 100644 --- a/scribble-demos/scrib/travel/src/travel/BookingS.java +++ b/scribble-demos/scrib/travel/src/travel/BookingS.java @@ -16,21 +16,22 @@ import java.io.IOException; import java.util.concurrent.ExecutionException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -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 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.channels.S.Booking_S_1; -import travel.Travel.Booking.channels.S.Booking_S_1_Cases; 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, ScribbleRuntimeException, ExecutionException, InterruptedException + public static void main(String[] args) throws IOException, + ScribRuntimeException, ExecutionException, InterruptedException { try (ScribServerSocket ss_C = new SocketChannelServer(8888); ScribServerSocket ss_A = new SocketChannelServer(9999)) @@ -38,7 +39,8 @@ public static void main(String[] args) throws IOException, ScribbleRuntimeExcept while (true) { Booking booking = new Booking(); - try (MPSTEndpoint se = new MPSTEndpoint<>(booking, Booking.S, new ObjectStreamFormatter())) + try (MPSTEndpoint se = new MPSTEndpoint<>(booking, + Booking.S, new ObjectStreamFormatter())) { //S.register(Booking.A, ss_A); diff --git a/scribble-demos/scrib/travel/src/travel/Travel.scr b/scribble-demos/scrib/travel/src/travel/Travel.scr index f2f0d9941..e7444b514 100644 --- a/scribble-demos/scrib/travel/src/travel/Travel.scr +++ b/scribble-demos/scrib/travel/src/travel/Travel.scr @@ -1,10 +1,10 @@ //$ ./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 scribble-demos/scrib/travel/src/travel/*.java -subpackages travel.Travel.Booking -d scribble-demos/scrib/travel/javadoc +//$ 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; -type "java.lang.Integer" from "rt.jar" as Int; -type "java.lang.String" from "rt.jar" as String; +data "java.lang.Integer" from "rt.jar" as Int; +data "java.lang.String" from "rt.jar" as String; //* diff --git a/scribble-demos/scrib/tutorial/src/tutorial/adder/Adder.scr b/scribble-demos/scrib/tutorial/src/tutorial/adder/Adder.scr index 9add83e44..15359f537 100644 --- a/scribble-demos/scrib/tutorial/src/tutorial/adder/Adder.scr +++ b/scribble-demos/scrib/tutorial/src/tutorial/adder/Adder.scr @@ -16,7 +16,7 @@ module tutorial.adder.Adder; -type "java.lang.Integer" from "rt.jar" as Int; +data "java.lang.Integer" from "rt.jar" as Int; global protocol Adder(role C, role S) { diff --git a/scribble-demos/scrib/tutorial/src/tutorial/adder/AdderC.java b/scribble-demos/scrib/tutorial/src/tutorial/adder/AdderC.java index 28bb6c659..2c2c1c3a4 100644 --- a/scribble-demos/scrib/tutorial/src/tutorial/adder/AdderC.java +++ b/scribble-demos/scrib/tutorial/src/tutorial/adder/AdderC.java @@ -19,15 +19,15 @@ import static tutorial.adder.Adder.Adder.Adder.Res; import static tutorial.adder.Adder.Adder.Adder.S; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.ObjectStreamFormatter; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +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.channels.C.Adder_C_1; -import tutorial.adder.Adder.Adder.channels.C.Adder_C_2; 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 { @@ -35,7 +35,7 @@ public static void main(String[] args) throws Exception { Adder adder = new Adder(); try (MPSTEndpoint client = new MPSTEndpoint<>(adder, C, new ObjectStreamFormatter())) { - client.connect(S, SocketChannelEndpoint::new, "localhost", 8888); + client.request(S, SocketChannelEndpoint::new, "localhost", 8888); int n = 10; System.out.println(n + "th Fibonacci number: " + fibo(new Adder_C_1(client), n)); diff --git a/scribble-demos/scrib/tutorial/src/tutorial/adder/AdderS.java b/scribble-demos/scrib/tutorial/src/tutorial/adder/AdderS.java index a17c474d6..be7359d94 100644 --- a/scribble-demos/scrib/tutorial/src/tutorial/adder/AdderS.java +++ b/scribble-demos/scrib/tutorial/src/tutorial/adder/AdderS.java @@ -21,17 +21,17 @@ import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -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 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.channels.S.Adder_S_1; -import tutorial.adder.Adder.Adder.channels.S.Adder_S_1_Cases; 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 { @@ -43,7 +43,7 @@ public static void main(String[] args) throws Exception { = new MPSTEndpoint<>(adder, S, new ObjectStreamFormatter())) { server.accept(ss, C); new AdderS().run(new Adder_S_1(server)); - } catch (ScribbleRuntimeException | IOException | ClassNotFoundException e) { + } catch (ScribRuntimeException | IOException | ClassNotFoundException e) { e.printStackTrace(); } } diff --git a/scribble-demos/scrib/twobuyer/src/twobuyer/TwoBuyer.scr b/scribble-demos/scrib/twobuyer/src/twobuyer/TwoBuyer.scr index 69c61841c..c9565fc2b 100644 --- a/scribble-demos/scrib/twobuyer/src/twobuyer/TwoBuyer.scr +++ b/scribble-demos/scrib/twobuyer/src/twobuyer/TwoBuyer.scr @@ -1,10 +1,10 @@ module twobuyer.TwoBuyer; -type "java.lang.Integer" from "rt.jar" as int; -type "java.lang.String" from "rt.jar" as String; -type "test.twobuyer.Address" from "test/twobuyer/Address.java" as Address; -type "test.twobuyer.Date" from "test/twobuyer/Date.java" as Date; +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) diff --git a/scribble-dist/pom.xml b/scribble-dist/pom.xml index a9e9d844a..87a484261 100644 --- a/scribble-dist/pom.xml +++ b/scribble-dist/pom.xml @@ -11,22 +11,19 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 - - org.scribble - parent - 0.4.4-SNAPSHOT - scribble-dist pom - scribble-dist - Scribble distribution. org.scribble scribble-core + + org.scribble + scribble-ast + org.scribble scribble-parser @@ -46,6 +43,14 @@ + + org.scribble + parent + 0.5.1-SNAPSHOT + ../pom.xml + + + @@ -68,4 +73,9 @@ + + + scribble-dist + Scribble distribution. + diff --git a/scribble-dist/src/main/resources/scribblec.sh b/scribble-dist/src/main/resources/scribblec.sh index 5f2df50b3..6de535a89 100644 --- a/scribble-dist/src/main/resources/scribblec.sh +++ b/scribble-dist/src/main/resources/scribblec.sh @@ -15,45 +15,56 @@ ## -# Config notes: +# Config: # -# - ANTLR: -# Set $ANTLR (below) to the location of the ANTLR 3 runtime jar, -# or add the jar to $DIR/$LIB assuming $DIR is the scribble-java root directory. -# (This script looks for ANTLR in those locations.) -# - +# $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 location (if no lib jar) -ANTLR= +# 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) + # or '/cygdrive/c/Users/[User]/.m2/repository/org/antlr/antlr-runtime/3.4/antlr-runtime-3.4.jar' + # (i.e., the Maven install location) -DIR=`dirname "$0"` # Default (script is in scribble-java rootdir) -#DIR=`dirname "$0"`/.. # (E.g., script is in rootdir/bin) +# 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 -#PRG=`basename "$0"` - -# Directory containing Scribble jars -LIB=lib +#if [ "$(uname | grep -c CYGWIN)" -ne 0 ]; then +# CYGWIN=1 +#fi +# +## usage() { - echo Usage: 'scribblec.sh [option]... [option]...' + echo 'Set $SCRIBBLE_HOME to the scribble-java root directory (default: current dir).' cat < Source Scribble module (.scr file) - -Options: - -h, --help Show this info and exit$ - -V Scribble debug info$ - --verbose Echo the java command$ +i.e., the directory that contains the scribble-java modules and/or lib directory. +Look inside the script for other settings. + +Usage: 'scribblec.sh [option]... [option]...' - -ip Scribble module import path$ + Source Scribble module (.scr file) - -oldwf Use the simpler syntactic protocol well-formedness +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 @@ -70,7 +81,7 @@ Options: -model Generate global model - -modelpng + -modelpng Draw global model as png (requires dot) -fair Assume fair output choices -umodel, -umodelpng (with appropriate args) "Unfair" variant @@ -84,64 +95,70 @@ Options: EOF } + +SEP=':' # Classpath separator +if [ "$WSL" = 1 ] || [ "$CYGWIN" = 1 ]; then + SEP=';' +fi + fixpath() { - windows=0 - - if [ `uname | grep -c CYGWIN` -ne 0 ]; then - windows=1 - fi - - cp="$1" - if [ "$windows" = 1 ]; then - cygpath -pw "$cp" - else - echo "$cp" - fi + 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" } -ARGS= +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")"\' -CLASSPATH=$DIR'/scribble-cli/target/classes/' -CLASSPATH=$CLASSPATH':'$DIR'/scribble-core/target/classes' -CLASSPATH=$CLASSPATH':'$DIR'/scribble-parser/target/classes' -CLASSPATH=$CLASSPATH':'$DIR'/scribble-codegen/target/classes' -CLASSPATH=$CLASSPATH':'$ANTLR -CLASSPATH=$CLASSPATH':'$DIR'/'$LIB'/antlr.jar' -CLASSPATH=$CLASSPATH':'$DIR'/'$LIB'/antlr-runtime.jar' -CLASSPATH=$CLASSPATH':'$DIR'/'$LIB'/commons-io.jar' -CLASSPATH=$CLASSPATH':'$DIR'/'$LIB'/scribble-cli.jar' -CLASSPATH=$CLASSPATH':'$DIR'/'$LIB'/scribble-core.jar' -CLASSPATH=$CLASSPATH':'$DIR'/'$LIB'/scribble-parser.jar' -CLASSPATH=$CLASSPATH':'$DIR'/'$LIB'/scribble-codegen.jar' -CLASSPATH=$CLASSPATH':'$DIR'/'$LIB'/stringtemplate.jar' -CLASSPATH="'"`fixpath "$CLASSPATH"`"'" usage=0 verbose=0 -dot=0 -nondot=0 +ARGS= while true; do case "$1" in "") break ;; - #-dot) - # # Should not be used in conjunction with other flags.. - # # ..that output to stdout - # ARGS="$ARGS '-fsm'" - # shift - # ARGS="$ARGS '$1'" - # shift - # ARGS="$ARGS '$1'" - # shift - # dot=$1 - # if [ "$dot" == '' ]; then - # echo '-dot missing output file name argument' - # exit 1 - # fi - # shift - # ;; -h) usage=1 break @@ -154,23 +171,6 @@ while true; do verbose=1 shift ;; - #-ip) - # ARGS="$ARGS '$1'" - # shift - # ;; - #-d) - # ARGS="$ARGS '$1'" - # shift - # ;; - #-subtypes) - # ARGS="$ARGS '$1'" - # shift - # ;; - #-*) - # nondot=1 - # ARGS="$ARGS '$1'" - # shift - # ;; *) ARGS="$ARGS '$1'" shift @@ -178,31 +178,21 @@ while true; do esac done -#if [ "$dot" != 0 ]; then -# if [ $nondot == 1 ]; then -# echo '-dot cannot be used in conjunction with other flags that output to stdout: ' $ARGS -# exit 1 -# fi -# ARGS="$ARGS |" -# ARGS="$ARGS dot" -# ARGS="$ARGS '-Tpng'" -# ARGS="$ARGS '-o'" -# ARGS="$ARGS '$dot'" -#fi +if [ "$usage" = 1 ] || [ -z "$ARGS" ]; then -if [ "$usage" = 1 ]; then - usage - exit 0 + usage + exit 0 fi -CMD='java -cp '$CLASSPATH' org.scribble.cli.CommandLine' + +CMD="$JAVA"' -cp '\'"$CLASSPATH"\'' org.scribble.cli.CommandLine' scribblec() { - eval $CMD "$@" + eval "$CMD" "$@" } if [ "$verbose" = 1 ]; then - echo $CMD "$ARGS" + echo "$CMD" "$ARGS" fi scribblec "$ARGS" 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-core/src/main/java/org/scribble/main/resource/AbstractResource.java b/scribble-main/src/main/java/org/scribble/main/resource/AbstractResource.java similarity index 100% rename from scribble-core/src/main/java/org/scribble/main/resource/AbstractResource.java rename to scribble-main/src/main/java/org/scribble/main/resource/AbstractResource.java diff --git a/scribble-core/src/main/java/org/scribble/main/resource/FileResource.java b/scribble-main/src/main/java/org/scribble/main/resource/FileResource.java similarity index 100% rename from scribble-core/src/main/java/org/scribble/main/resource/FileResource.java rename to scribble-main/src/main/java/org/scribble/main/resource/FileResource.java diff --git a/scribble-core/src/main/java/org/scribble/main/resource/InlineResource.java b/scribble-main/src/main/java/org/scribble/main/resource/InlineResource.java similarity index 89% rename from scribble-core/src/main/java/org/scribble/main/resource/InlineResource.java rename to scribble-main/src/main/java/org/scribble/main/resource/InlineResource.java index 54bf61842..b1ced5837 100644 --- a/scribble-core/src/main/java/org/scribble/main/resource/InlineResource.java +++ b/scribble-main/src/main/java/org/scribble/main/resource/InlineResource.java @@ -17,7 +17,7 @@ import java.nio.charset.StandardCharsets; -// Module supplied to tool directly as a String arg. +// Module supplied directly as a String arg. public class InlineResource extends AbstractResource { //private final String res; @@ -33,7 +33,8 @@ public InlineResource(String res) { super(Resource.INLINE_LOCATION); //this.res = res; - this._inputStream = new ByteArrayInputStream(res.getBytes(StandardCharsets.UTF_8)); + this._inputStream = new ByteArrayInputStream( + res.getBytes(StandardCharsets.UTF_8)); } @Override diff --git a/scribble-core/src/main/java/org/scribble/main/resource/Resource.java b/scribble-main/src/main/java/org/scribble/main/resource/Resource.java similarity index 93% rename from scribble-core/src/main/java/org/scribble/main/resource/Resource.java rename to scribble-main/src/main/java/org/scribble/main/resource/Resource.java index 8829ddc30..ccb388d6a 100644 --- a/scribble-core/src/main/java/org/scribble/main/resource/Resource.java +++ b/scribble-main/src/main/java/org/scribble/main/resource/Resource.java @@ -17,6 +17,8 @@ /** * This class represents the resource. + * + * CHECKME: maybe refactor core Resource classes out of cli package (generalise) * */ public interface Resource 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-core/src/main/java/org/scribble/main/ModuleLoader.java b/scribble-main/src/main/java/org/scribble/main/resource/loader/ModuleLoader.java similarity index 84% rename from scribble-core/src/main/java/org/scribble/main/ModuleLoader.java rename to scribble-main/src/main/java/org/scribble/main/resource/loader/ModuleLoader.java index 158900adf..77be9862c 100644 --- a/scribble-core/src/main/java/org/scribble/main/ModuleLoader.java +++ b/scribble-main/src/main/java/org/scribble/main/resource/loader/ModuleLoader.java @@ -11,13 +11,13 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.main; +package org.scribble.main.resource.loader; -import org.scribble.ast.AstFactory; import org.scribble.ast.Module; +import org.scribble.core.type.name.ModuleName; import org.scribble.main.resource.Resource; -import org.scribble.type.name.ModuleName; import org.scribble.util.Pair; +import org.scribble.util.ScribException; import org.scribble.util.ScribParserException; @@ -38,6 +38,7 @@ public interface ModuleLoader * @return The module, or null if not found * @throws ScribParserException */ - public Pair loadModule(ModuleName modname, AstFactory af) throws ScribParserException, ScribbleException; + 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-core/src/main/java/org/scribble/main/resource/IResourceLocator.java b/scribble-main/src/main/java/org/scribble/main/resource/locator/IResourceLocator.java similarity index 77% rename from scribble-core/src/main/java/org/scribble/main/resource/IResourceLocator.java rename to scribble-main/src/main/java/org/scribble/main/resource/locator/IResourceLocator.java index 3b9ae463c..06b845038 100644 --- a/scribble-core/src/main/java/org/scribble/main/resource/IResourceLocator.java +++ b/scribble-main/src/main/java/org/scribble/main/resource/locator/IResourceLocator.java @@ -11,11 +11,12 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.main.resource; +package org.scribble.main.resource.locator; import java.nio.file.Path; -import org.scribble.main.ScribbleException; +import org.scribble.main.resource.Resource; +import org.scribble.util.ScribException; /** @@ -32,5 +33,6 @@ public interface IResourceLocator * @return The resource, or null if not found */ - Resource getResource(Path path) throws ScribbleException; // Path should be made more abstract, e.g. some kind of URI (cf., Resource.getLocation) + 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-core/src/main/java/org/scribble/main/resource/ResourceLocator.java b/scribble-main/src/main/java/org/scribble/main/resource/locator/ResourceLocator.java similarity index 93% rename from scribble-core/src/main/java/org/scribble/main/resource/ResourceLocator.java rename to scribble-main/src/main/java/org/scribble/main/resource/locator/ResourceLocator.java index 00438bfca..86f2c69af 100644 --- a/scribble-core/src/main/java/org/scribble/main/resource/ResourceLocator.java +++ b/scribble-main/src/main/java/org/scribble/main/resource/locator/ResourceLocator.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.main.resource; +package org.scribble.main.resource.locator; public abstract class ResourceLocator implements IResourceLocator diff --git a/scribble-parser/pom.xml b/scribble-parser/pom.xml index 09d2e2c42..3f0617c98 100644 --- a/scribble-parser/pom.xml +++ b/scribble-parser/pom.xml @@ -1,14 +1,15 @@ 4.0.0 + + scribble-parser jar - scribble-parser org.scribble parent - 0.4.4-SNAPSHOT + 0.5.1-SNAPSHOT ../pom.xml @@ -18,12 +19,18 @@ scribble-core + + org.scribble + scribble-ast + + org.antlr antlr-runtime + @@ -41,4 +48,7 @@ + + scribble-parser + 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 index df73fafd3..303606541 100644 --- a/scribble-parser/src/main/antlr3/org/scribble/parser/antlr/Scribble.g +++ b/scribble-parser/src/main/antlr3/org/scribble/parser/antlr/Scribble.g @@ -1,281 +1,243 @@ -/* - * > scribble-java +/** + * 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 = CommonTree; - //backtrack = true; // backtracking disabled by default? Is it bad to require this option? - //memoize = true; + language = Java; + output = AST; + ASTLabelType = ScribNodeBase; } tokens { - /* - * Parser input constants (lexer output; keywords, Section 2.4) - */ - - MODULE_KW = 'module'; - IMPORT_KW = 'import'; - TYPE_KW = 'type'; - PROTOCOL_KW = 'protocol'; - GLOBAL_KW = 'global'; - LOCAL_KW = 'local'; - EXPLICIT_KW = 'explicit'; - AUX_KW = 'aux'; - ROLE_KW = 'role'; - ACCEPT_KW = 'accept'; - SELF_KW = 'self'; - SIG_KW = 'sig'; - //INSTANTIATES_KW = 'instantiates'; - AS_KW = 'as'; - - CONNECT_KW = 'connect'; - DISCONNECT_KW = 'disconnect'; - WRAP_KW = 'wrap'; - FROM_KW = 'from'; - TO_KW = 'to'; - CHOICE_KW = 'choice'; - AT_KW = 'at'; - OR_KW = 'or'; - REC_KW = 'rec'; - CONTINUE_KW = 'continue'; - //PAR_KW = 'par'; - AND_KW = 'and'; // Needed for disconnect - /*INTERRUPTIBLE_KW = 'interruptible'; - WITH_KW = 'with'; - BY_KW = '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") * / - THROWS_KW = 'throws'; - CATCHES_KW = 'catches';*/ - DO_KW = 'do'; - //SPAWN_KW = '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) - */ - - // Purely util constants -- not parsed as node types - - KIND_MESSAGESIGNATURE = 'KIND_MESSAGESIGNATURE'; - KIND_PAYLOADTYPE = 'KIND_PAYLOADTYPE'; - - - // "Node type" constants -- but not parsed "directly" by AntlrToScribParser - - EMPTY_ALIAS = 'EMTPY_ALIAS'; - /*EMPTY_SCOPENAME = '__empty_scopename'; - NO_SCOPE = '__no_scope';*/ - //EMPTY_PACKAGENAME = '__empty_packagebame'; - EMPTY_OPERATOR = 'EMPTY_OPERATOR'; - - //EMPTY_PARAMETERDECLLIST = '__empty_parameterdecllist'; - //EMPTY_ARGUMENTINSTANTIATIONLIST = '__empty_argumentinstantiationlist'; - /*EMPTY_LOCALTHROW = '__empty_localthrow'; - EMPTY_LOCAL_CATCHES = '__empty_local_catch';*/ - - //NAME = 'name'; - AMBIGUOUSNAME = 'AMBIGUOUSNAME'; - QUALIFIEDNAME = 'QUALIFIEDNAME'; - //PACKAGENAME = 'package-name'; - //FULLMODULENAME = 'full-module-name'; - //SIMPLEMEMBERNAME = 'simple-member-name'; - //QUALIFIEDMEMBERNAME = 'qualified-member-name'; - - MESSAGESIGNATURE = 'MESSAGESIGNATURE'; - DELEGATION = 'DELEGATION'; - - - // Parsed "directly" by AntlrToScribParser - - PAYLOAD = 'PAYLOAD'; - //PAYLOADELEMENT = 'payloadelement'; - - //MODULE = 'module'; // Probably a keyword clash - MODULE = 'MODULE'; - //PACKAGEDECL = 'package-decl'; - MODULEDECL = 'MODULEDECL'; - //IMPORTDECL = 'import-decl'; - //FROMIMPORTDECL = 'from-import-decl'; - IMPORTMODULE = 'IMPORTMODULE'; - IMPORTMEMBER = 'IMPORTMEMBER'; - PAYLOADTYPEDECL = 'PAYLOADTYPEDECL'; - MESSAGESIGNATUREDECL = 'MESSAGESIGNATUREDECL'; - ROLEDECLLIST = 'ROLEDECLLIST'; - ROLEDECL = 'ROLEDECL'; - PARAMETERDECLLIST = 'PARAMETERDECLLIST'; - PARAMETERDECL = 'PARAMETERDECL'; - ROLEINSTANTIATIONLIST = 'ROLEINSTANTIATIONLIST'; - ROLEINSTANTIATION = 'ROLEINSTANTIATION'; // FIXME: not consistent with arginstas/payloadeles - ARGUMENTINSTANTIATIONLIST = 'ARGUMENTINSTANTIATIONLIST'; - //ARGUMENTINSTANTIATION = 'argument-instantiation'; - //CONNECTDECL = 'connect-decl'; - - GLOBALPROTOCOLDECL = 'GLOBALPROTOCOLDECL'; - GLOBALPROTOCOLDECLMODS = 'GLOBALPROTOCOLDECLMODS'; - GLOBALPROTOCOLHEADER = 'GLOBALPROTOCOLHEADER'; - GLOBALPROTOCOLDEF = 'GLOBALPROTOCOLDEF'; - GLOBALPROTOCOLBLOCK = 'GLOBALPROTOCOLBLOCK'; - GLOBALINTERACTIONSEQUENCE = 'GLOBALINTERACTIONSEQUENCE'; - GLOBALMESSAGETRANSFER = 'GLOBALMESSAGETRANSFER'; - GLOBALCONNECT = 'GLOBALCONNECT'; - GLOBALDISCONNECT = 'GLOBALDISCONNECT'; - GLOBALWRAP = 'GLOBALWRAP'; - GLOBALCHOICE = 'GLOBALCHOICE'; - GLOBALRECURSION = 'GLOBALRECURSION'; - GLOBALCONTINUE = 'GLOBALCONTINUE'; - /*GLOBALPARALLEL = 'GLOBALPARALLEL'; - GLOBALINTERRUPTIBLE = 'GLOBALINTERRUPTIBLE'; - GLOBALINTERRUPT = 'GLOBALINTERRUPT';*/ - GLOBALDO = 'GLOBALDO'; - - /*LOCALPROTOCOLDECL = 'local-protocol-decl'; - LOCALROLEDECLLIST = 'local-role-decl-list'; - LOCALROLEDECL = 'local-role-decl'; - SELFDECL = 'self-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'; - LOCALTHROWS = 'local-throws'; - LOCALCATCHES = 'local-catches'; - LOCALSEND = 'local-send'; - LOCALRECEIVE = 'local-receive';*/ + /* 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'; } -// Has to come after tokens? -@parser::header +@lexer::header { - package org.scribble.parser.antlr; - - //import org.scribble.main.RuntimeScribbleException; + package org.scribble.parser.antlr; } -@lexer::header + +@lexer::members { - package org.scribble.parser.antlr; - - //import org.scribble.main.RuntimeScribbleException; + @Override + public void displayRecognitionError(String[] tokenNames, + RecognitionException e) + { + super.displayRecognitionError(tokenNames, e); + System.exit(1); + } } -/*// Was swallowing parser error messages -@members { - //private org.scribble.logging.IssueLogger _logger=null; - private String _document=null; - private boolean _errorOccurred=false; - - /*public void setLogger(org.scribble.logging.IssueLogger logger) { - _logger = logger; - }* / - - public void setDocument(String doc) { - _document = doc; - } - - public void emitErrorMessage(String mesg) { - /*if (_logger == null) { - super.emitErrorMessage(mesg); - } else { - _logger.error(org.scribble.parser.antlr.ANTLRMessageUtil.getMessageText(mesg), - org.scribble.parser.antlr.ANTLRMessageUtil.getProperties(mesg, _document)); - }* / - _errorOccurred = true; - } - - public boolean isErrorOccurred() { - return(_errorOccurred); - } -}*/ -@parser::members +// Must come after tokens? +@parser::header { - /*@Override - public void reportError(RecognitionException e) - { - super.reportError(e); - //throw new RuntimeScribbleException(e.getMessage()); - //System.exit(1); - }*/ - - // Abort tool run on parsing errors (and display user-friendly message) -- obsoletes CommonErrorNode check? - @Override - public void displayRecognitionError(String[] tokenNames, RecognitionException e) - { - /*String hdr = getErrorHeader(e); - String msg = getErrorMessage(e, tokenNames); - //throw new RuntimeException(hdr + ":" + msg); - System.err.println(hdr + ":" + msg);*/ - super.displayRecognitionError(tokenNames, e); - System.exit(1); - } + 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; } -@lexer::members + +@parser::members { - /*@Override - public void reportError(RecognitionException e) + // Abort tool run on parsing errors (and display user-friendly message) -- obsoletes CommonErrorNode check? + @Override + public void displayRecognitionError(String[] tokenNames, + RecognitionException e) { - super.reportError(e); - //throw new RuntimeScribbleException(e.getMessage()); - //System.exit(1); - }*/ + super.displayRecognitionError(tokenNames, e); + System.exit(1); + } - @Override - public void displayRecognitionError(String[] tokenNames, RecognitionException e) - { - /*String hdr = getErrorHeader(e); - String msg = getErrorMessage(e, tokenNames); - //throw new RuntimeException(hdr + ":" + msg); - System.err.println(hdr + ":" + msg);*/ - 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; } - ; /** @@ -290,37 +252,37 @@ COMMENT: LINE_COMMENT: '//' ~('\n'|'\r')* '\r'? '\n' - { + { $channel=HIDDEN; } ; + /** * Section 2.3 Identifiers */ -IDENTIFIER: +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 - */ -// (LETTER | DIGIT)* + /* 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 + '&' | '?' | '!' | 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) -EXTIDENTIFIER: - '\"' (LETTER | DIGIT | SYMBOL)* '\"' - //(LETTER | DIGIT | SYMBOL)* +EXTID: + '\"' (LETTER | DIGIT | SYMBOL)* '\"' ; + //(LETTER | DIGIT | SYMBOL)* // Not working fragment LETTER: 'a'..'z' | 'A'..'Z' @@ -339,637 +301,393 @@ 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] ? -simplename: - IDENTIFIER -/*-> - ^(SIMPLENAME IDENTIFIER)*/ -; - -//annotationname: simplename; -parametername: simplename; -recursionvarname: simplename; -rolename: simplename; -scopename: simplename; - -ambiguousname: - simplename --> - ^(AMBIGUOUSNAME simplename) -; +// "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+) ; -simplemodulename: simplename; -simplepayloadtypename: simplename; -simplemessagesignaturename: simplename; -simpleprotocolname: simplename; -simplemembername: simplename; // Only for member declarations - -qualifiedname: - IDENTIFIER ('.' IDENTIFIER)* --> - ^(QUALIFIEDNAME IDENTIFIER+) -; +// Compound only (cf., e.g., gprotoname; cf. simpledataname) +qualifieddataname: t=ID '.' ID ('.' ID)* -> ^(DATA_NAME[$t] ID+) ; -packagename: qualifiedname; -modulename: qualifiedname; -membername: qualifiedname; - -protocolname: membername; -payloadtypename: membername; -messagesignaturename: membername; +// 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 - */ -module: - moduledecl importdecl* datatypedecl* protocoldecl* EOF --> - ^(MODULE moduledecl importdecl* datatypedecl* protocoldecl*) -; - - -/** * Section 3.2.3 Module Declarations */ -moduledecl: - MODULE_KW modulename ';' +// "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 -> - ^(MODULEDECL modulename) + ^(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 */ -importdecl: - importmodule -| - importmember -; - importmodule: - IMPORT_KW modulename ';' + t=IMPORT_KW modulename (AS_KW alias=simplemodulename)? ';' -> - ^(IMPORTMODULE modulename EMPTY_ALIAS) -| - IMPORT_KW modulename AS_KW simplemodulename ';' --> - ^(IMPORTMODULE modulename simplemodulename) -; - -importmember: - FROM_KW modulename IMPORT_KW simplemembername ';' --> - ^(IMPORTMEMBER modulename simplemembername EMPTY_ALIAS) -| - FROM_KW modulename IMPORT_KW simplemembername AS_KW simplemembername ';' --> - ^(IMPORTMEMBER modulename simplemembername simplemembername) + ^(IMPORTMODULE[$t] modulename $alias?) ; /** - * //Section 3.4 Payload Type Declarations - * Data Declarations + * Section 3.4 "Non Protocol" Declarations */ -datatypedecl: - payloadtypedecl -| - messagesignaturedecl -; +nonprotodecl: + datadecl | sigdecl ; -payloadtypedecl: - TYPE_KW '<' IDENTIFIER '>' EXTIDENTIFIER FROM_KW EXTIDENTIFIER AS_KW simplepayloadtypename ';' +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 ';' -> - ^(PAYLOADTYPEDECL IDENTIFIER EXTIDENTIFIER EXTIDENTIFIER simplepayloadtypename) + // alias first to be uniform with other NameDeclNode (getRawNameNodeChild) + ^(DATADECL[$t] $alias $schema $extName $extSource) ; -messagesignaturedecl: - SIG_KW '<' IDENTIFIER '>' EXTIDENTIFIER FROM_KW EXTIDENTIFIER AS_KW simplemessagesignaturename ';' +sigdecl: + t=SIG_KW '<' schema=ID '>' extName=EXTID FROM_KW extSource=EXTID AS_KW + alias=simplesigname ';' -> - ^(MESSAGESIGNATUREDECL IDENTIFIER EXTIDENTIFIER EXTIDENTIFIER simplemessagesignaturename) + // alias first to be uniform with other NameDeclNode (getRawNameNodeChild) + ^(SIGDECL[$t] $alias $schema $extName $extSource) ; /** * Section 3.5 Message Signatures */ -/*messageoperator: - IDENTIFIER -;*/ +siglit: + opname '(' payelems ')' -> ^(SIG_LIT opname payelems) +; +// CHECKME: how to apply [$t] in such situations? -messagesignature: - '(' payload ')' --> - ^(MESSAGESIGNATURE EMPTY_OPERATOR payload) +payelems: + -> ^(PAYELEM_LIST) | - //messageoperator '(' payload ')' // Doesn't work (conflict with IDENTIFIER?) - IDENTIFIER '(' payload ')' --> - ^(MESSAGESIGNATURE IDENTIFIER payload) + 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) | - '(' ')' --> - ^(MESSAGESIGNATURE EMPTY_OPERATOR ^(PAYLOAD)) + ambigname -> ^(UNARY_PAYELEM ambigname) | - IDENTIFIER '(' ')' --> - ^(MESSAGESIGNATURE IDENTIFIER ^(PAYLOAD)) + qualifieddataname -> ^(UNARY_PAYELEM qualifieddataname) ; +// { parsePayloadElem($qualifiedname.tree) } // Use ".text" instead of ".tree" for token String + -payload: - payloadelement (',' payloadelement)* --> - ^(PAYLOAD payloadelement+) -; - -// Payload type names need disambiguation pass (also do args) -payloadelement: -/* ambiguousname // Parser doesn't distinguish simple from qualified properly, even with backtrack -|*/ - qualifiedname // This case subsumes simple names // FIXME: ambiguousqualifiedname (or ambiguousname should just be qualified) -| - protocolname '@' rolename --> - ^(DELEGATION rolename protocolname) -; /** * Section 3.6 Protocol Declarations */ -protocoldecl: - globalprotocoldecl -/*| - localprotocoldecl*/ -; +protodecl: + gprotodecl ; /** * Section 3.7 Global Protocol Declarations */ -globalprotocoldecl: - globalprotocolheader globalprotocoldefinition --> - ^(GLOBALPROTOCOLDECL globalprotocolheader globalprotocoldefinition) -| - globalprotocoldeclmodifiers globalprotocolheader globalprotocoldefinition // HACK: backwards compat for "implicit" connections +gprotodecl: + protomods gprotoheader gprotodef -> - ^(GLOBALPROTOCOLDECL globalprotocolheader globalprotocoldefinition globalprotocoldeclmodifiers) + ^(GPROTODECL protomods gprotoheader gprotodef) ; - -globalprotocoldeclmodifiers: - AUX_KW EXPLICIT_KW --> - ^(GLOBALPROTOCOLDECLMODS AUX_KW EXPLICIT_KW) -| - EXPLICIT_KW --> - ^(GLOBALPROTOCOLDECLMODS EXPLICIT_KW) -| - AUX_KW --> - ^(GLOBALPROTOCOLDECLMODS AUX_KW) + +// "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) ; -globalprotocolheader: - GLOBAL_KW PROTOCOL_KW simpleprotocolname roledecllist +gprotoheader: + t=GLOBAL_KW PROTOCOL_KW simplegprotoname paramdecls roledecls -> - ^(GLOBALPROTOCOLHEADER simpleprotocolname ^(PARAMETERDECLLIST) roledecllist) -| - GLOBAL_KW PROTOCOL_KW simpleprotocolname parameterdecllist roledecllist --> - ^(GLOBALPROTOCOLHEADER simpleprotocolname parameterdecllist roledecllist) + ^(GPROTOHEADER[$t] simplegprotoname paramdecls roledecls) ; +// N.B. intermed translation uses full proto name -roledecllist: - '(' roledecl (',' roledecl)* ')' --> - ^(ROLEDECLLIST roledecl+) -; +roledecls: + t='(' roledecl (',' roledecl)* ')' -> ^(ROLEDECL_LIST[$t] roledecl+) ; roledecl: - ROLE_KW rolename --> - ^(ROLEDECL rolename) -; + t=ROLE_KW rolename -> ^(ROLEDECL[$t] rolename) ; -parameterdecllist: - '<' parameterdecl (',' parameterdecl)* '>' --> - ^(PARAMETERDECLLIST parameterdecl+) +paramdecls: + -> ^(PARAMDECL_LIST) +| + t='<' (paramdecl (',' paramdecl)*)? '>' -> ^(PARAMDECL_LIST[$t] paramdecl*) ; -parameterdecl: - TYPE_KW parametername --> - ^(PARAMETERDECL KIND_PAYLOADTYPE parametername) +paramdecl: dataparamdecl | sigparamdecl ; + +dataparamdecl: + t=TYPE_KW dataparamname -> ^(DATAPARAMDECL[$t] dataparamname) | - SIG_KW parametername --> - ^(PARAMETERDECL KIND_MESSAGESIGNATURE parametername) + 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 */ -globalprotocoldefinition: - globalprotocolblock --> - ^(GLOBALPROTOCOLDEF globalprotocolblock) -; +gprotodef: + gprotoblock -> ^(GPROTODEF gprotoblock) ; /** * Section 3.7.3 Global Interaction Sequences and Blocks */ -globalprotocolblock: - '{' globalinteractionsequence '}' --> - ^(GLOBALPROTOCOLBLOCK globalinteractionsequence) -/*| - '(' connectdecl ')' '{' globalinteractionsequence '}' --> - ^(GLOBALPROTOCOLBLOCK globalinteractionsequence connectdecl)*/ +gprotoblock: + t='{' gseq '}' -> ^(GPROTOBLOCK[$t] gseq) ; -globalinteractionsequence: - globalinteraction* --> - ^(GLOBALINTERACTIONSEQUENCE globalinteraction*) +gseq: + ginteraction* -> ^(GINTERSEQ ginteraction*) ; -globalinteraction: - globalmessagetransfer -| - globalchoice -| - globalrecursion -| - globalcontinue -| - globaldo -| - globalconnect -| - globaldisconnect -| - globalwrap -; -/*| - globalparallel -| - globalinterruptible*/ +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 */ -globalmessagetransfer: +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 )* ';' -> - ^(GLOBALMESSAGETRANSFER message rolename rolename+) + ^(GMSGTRANSFER message rolename+) ; +// TODO: multisend -message: - messagesignature -| - ambiguousname // FIXME: qualified name -/*| - messagesignaturename // qualified messagesignaturename subsumes parametername case -| - parametername*/ -; - -globalconnect: - //message CONNECT_KW rolename TO_KW rolename - CONNECT_KW rolename TO_KW rolename ';' +gconnect: + message CONNECT_KW rolename TO_KW rolename ';' -> - ^(GLOBALCONNECT rolename rolename ^(MESSAGESIGNATURE EMPTY_OPERATOR ^(PAYLOAD))) // Empty message sig duplicated from messagesignature + ^(GCONNECT message rolename rolename) | - message CONNECT_KW rolename TO_KW rolename ';' + t=CONNECT_KW rolename TO_KW rolename ';' -> - ^(GLOBALCONNECT rolename rolename message) + ^(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? ; -/* '(' connectdecl (',' connectdecl)* ')' --> - ^(CONNECTDECLLIST connectdecl+) -;* / - '(' connectdecl ')' -*/ - -/*connectdecl: - CONNECT_KW rolename '->>' rolename --> - ^(CONNECTDECL rolename rolename) -;*/ -globaldisconnect: - DISCONNECT_KW rolename AND_KW rolename ';' +gdisconnect: + t=DISCONNECT_KW rolename AND_KW rolename ';' -> - ^(GLOBALDISCONNECT rolename rolename ) + ^(GDCONN[$t] rolename rolename) ; -globalwrap: - //message CONNECT_KW rolename TO_KW rolename - WRAP_KW rolename TO_KW rolename ';' +gwrap: + t=WRAP_KW rolename TO_KW rolename ';' -> - ^(GLOBALWRAP rolename rolename) + ^(GWRAP[$t] rolename rolename) ; /** * Section 3.7.5 Global Choice */ -globalchoice: - CHOICE_KW AT_KW rolename globalprotocolblock (OR_KW globalprotocolblock)* +gchoice: + t=CHOICE_KW AT_KW rolename gprotoblock (OR_KW gprotoblock)* -> - ^(GLOBALCHOICE rolename globalprotocolblock+) + ^(GCHOICE[$t] rolename gprotoblock+) ; /** * Section 3.7.6 Global Recursion */ -globalrecursion: - REC_KW recursionvarname globalprotocolblock +grecursion: + t=REC_KW recvarname gprotoblock -> - ^(GLOBALRECURSION recursionvarname globalprotocolblock) + ^(GRECURSION[$t] recvarname gprotoblock) ; -globalcontinue: - CONTINUE_KW recursionvarname ';' +gcontinue: + t=CONTINUE_KW recvarname ';' -> - ^(GLOBALCONTINUE recursionvarname) + ^(GCONTINUE[$t] recvarname) ; -/* - * Section 3.7.7 Global Parallel - * / -globalparallel: - PAR_KW globalprotocolblock (AND_KW globalprotocolblock)* --> - ^(GLOBALPARALLEL globalprotocolblock+) -;*/ - - -/* - * Section 3.7.8 Global Interruptible - * / -globalinterruptible: - INTERRUPTIBLE_KW globalprotocolblock WITH_KW '{' globalinterrupt* '}' --> - ^(GLOBALINTERRUPTIBLE EMPTY_SCOPENAME globalprotocolblock globalinterrupt*) -| - INTERRUPTIBLE_KW scopename globalprotocolblock WITH_KW '{' (globalinterrupt)* '}' --> - ^(GLOBALINTERRUPTIBLE scopename globalprotocolblock globalinterrupt*) -; - -globalinterrupt: - message (',' message)* BY_KW rolename ';' --> - ^(GLOBALINTERRUPT rolename message+) -;*/ - - /** * Section 3.7.9 Global Do */ -globaldo: - DO_KW protocolname roleinstantiationlist ';' --> - ^(GLOBALDO protocolname ^(ARGUMENTINSTANTIATIONLIST) roleinstantiationlist) -| - DO_KW protocolname argumentinstantiationlist roleinstantiationlist ';' +gdo: + DO_KW gprotoname nonroleargs roleargs ';' -> - ^(GLOBALDO protocolname argumentinstantiationlist roleinstantiationlist) + ^(GDO gprotoname nonroleargs roleargs) ; -roleinstantiationlist: - '(' roleinstantiation (',' roleinstantiation)* ')' --> - ^(ROLEINSTANTIATIONLIST roleinstantiation+) +roleargs: + t='(' rolearg (',' rolearg)* ')' -> ^(ROLEARG_LIST[$t] rolearg+) ; -roleinstantiation: - rolename --> - ^(ROLEINSTANTIATION rolename) // FIXME: not consistent with arginstas/payloadeles -; +rolearg: + rolename -> ^(ROLEARG rolename) ; -argumentinstantiationlist: - '<' argumentinstantiation (',' argumentinstantiation)* '>' --> - ^(ARGUMENTINSTANTIATIONLIST argumentinstantiation+) -; - -// Like PayloadElement, simple names need disambiguation -argumentinstantiation: - //message - // Grammatically same as message, but argument case can also be a payload type - messagesignature -/*| - ambiguousname // As for payloadelement: parser doesn't distinguish simple from qualified properly, even with backtrack*/ +nonroleargs: + -> ^(NONROLEARG_LIST) | - qualifiedname + t='<' (nonrolearg (',' nonrolearg)*)? '>' -> ^(NONROLEARG_LIST[$t] nonrolearg*) ; - -/* - * Section 3.8 Local Protocol Declarations - * / -localprotocoldecl: - localprotocolheader localprotocoldefinition --> - ^(LOCALPROTOCOLDECL localprotocolheader localprotocoldefinition) -; - -localprotocolheader: - LOCAL_KW PROTOCOL_KW simpleprotocolname localroledecllist --> - //simpleprotocolname EMPTY_PARAMETERDECLLIST localroledecllist - simpleprotocolname ^(PARAMETERDECLLIST) localroledecllist +// Grammatically same as message, but qualifiedname case may also be a payload type +nonrolearg: + siglit -> ^(NONROLEARG siglit) | - LOCAL_KW PROTOCOL_KW simpleprotocolname parameterdecllist localroledecllist --> - simpleprotocolname parameterdecllist localroledecllist -; - -localroledecllist: - '(' localroledecl (',' localroledecl)* ')' --> - ^(LOCALROLEDECLLIST localroledecl+) -; - -localroledecl: - roledecl + ambigname -> ^(NONROLEARG ambigname) | - SELF_KW rolename --> - ^(SELFDECL rolename) + qualifieddataname -> ^(NONROLEARG qualifieddataname) // FIXME: sig name -- need an ambig qualified name ; +// { parseNonRoleArg($qualifiedname.tree) } // Like payelem, simple names need disambiguation -/** - * Section 3.8.1 Local Protocol Definitions - * / -localprotocoldefinition: - localprotocolblock --> - ^(LOCALPROTOCOLDEF localprotocolblock) -; -/** - * 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 -; -/** - * Section 3.8.4 Local Send and Receive - * / -localsend: - message TO_KW rolename (',' rolename)* ';' --> - ^(LOCALSEND message rolename+) -; -localreceive: - message FROM_KW IDENTIFIER ';' --> - ^(LOCALRECEIVE message IDENTIFIER) -; -/** - * Section 3.8.5 Local Choice - * / -localchoice: - CHOICE_KW AT_KW rolename localprotocolblock (OR_KW localprotocolblock)* --> - ^(LOCALCHOICE rolename localprotocolblock+) -; -/** - * Section 3.8.6 Local Recursion - * / -localrecursion: - REC_KW recursionvarname localprotocolblock --> - ^(LOCALRECURSION recursionvarname localprotocolblock) -; -localcontinue: - CONTINUE_KW recursionvarname ';' --> - ^(LOCALCONTINUE recursionvarname) -; -/** - * Section 3.8.7 Local Parallel - * / -localparallel: - PAR_KW localprotocolblock (AND_KW localprotocolblock)* --> - ^(LOCALPARALLEL localprotocolblock+) -; -/** - * Section 3.8.8 Local Interruptible - * / -localinterruptible: - INTERRUPTIBLE_KW scopename localprotocolblock WITH_KW '{' localcatches* '}' --> - ^(LOCALINTERRUPTIBLE scopename localprotocolblock EMPTY_LOCALTHROW localcatches*) -| - INTERRUPTIBLE_KW scopename localprotocolblock WITH_KW '{' localthrows localcatches* '}' --> - ^(LOCALINTERRUPTIBLE scopename localprotocolblock localthrows localcatches*) -; -/*localthrowandorcatch: - localthrow (localcatch)* -| - (localcatch)+ -;* / -localthrows: - THROWS_KW message (',' message)* TO_KW rolename (',' rolename)* ';' --> - ^(LOCALTHROWS rolename+ TO_KW message+) -; -localcatches: - CATCHES_KW message (',' message)* FROM_KW rolename ';' --> - ^(LOCALCATCHES rolename message+) -; -/** - * Section 3.8.9 Local Do - * / -localdo: - DO_KW protocolname roleinstantiationlist ';' --> - //^(LOCALDO NO_SCOPE protocolname EMPTY_ARGUMENTINSTANTIATIONLIST roleinstantiationlist) - ^(LOCALDO NO_SCOPE protocolname ^(ARGUMENTINSTANTIATIONLIST) roleinstantiationlist) -| - DO_KW protocolname argumentinstantiationlist roleinstantiationlist ';' --> - ^(LOCALDO NO_SCOPE protocolname argumentinstantiationlist roleinstantiationlist) -| - DO_KW scopename ':' protocolname roleinstantiationlist ';' --> - //^(LOCALDO scopename protocolname EMPTY_ARGUMENTINSTANTIATIONLIST roleinstantiationlist) - ^(LOCALDO scopename protocolname ^(ARGUMENTINSTANTIATIONLIST) roleinstantiationlist) -| - DO_KW scopename ':' protocolname argumentinstantiationlist roleinstantiationlist ';' --> - ^(LOCALDO scopename protocolname argumentinstantiationlist roleinstantiationlist) -; -*/ +/* +@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/main/java/org/scribble/parser/scribble/AntlrToScribParser.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/AntlrToScribParser.java deleted file mode 100644 index 659e5e239..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/AntlrToScribParser.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble; - -import java.util.List; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonErrorNode; -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.ScribNode; -import org.scribble.parser.scribble.ScribbleAntlrConstants.AntlrNodeType; -import org.scribble.parser.scribble.ast.AntlrDataTypeDecl; -import org.scribble.parser.scribble.ast.AntlrImportModule; -import org.scribble.parser.scribble.ast.AntlrMessageSig; -import org.scribble.parser.scribble.ast.AntlrMessageSigDecl; -import org.scribble.parser.scribble.ast.AntlrModule; -import org.scribble.parser.scribble.ast.AntlrModuleDecl; -import org.scribble.parser.scribble.ast.AntlrNonRoleArgList; -import org.scribble.parser.scribble.ast.AntlrNonRoleParamDecl; -import org.scribble.parser.scribble.ast.AntlrNonRoleParamDeclList; -import org.scribble.parser.scribble.ast.AntlrPayloadElemList; -import org.scribble.parser.scribble.ast.AntlrRoleArg; -import org.scribble.parser.scribble.ast.AntlrRoleArgList; -import org.scribble.parser.scribble.ast.AntlrRoleDecl; -import org.scribble.parser.scribble.ast.AntlrRoleDeclList; -import org.scribble.parser.scribble.ast.global.AntlrGChoice; -import org.scribble.parser.scribble.ast.global.AntlrGConnect; -import org.scribble.parser.scribble.ast.global.AntlrGContinue; -import org.scribble.parser.scribble.ast.global.AntlrGDisconnect; -import org.scribble.parser.scribble.ast.global.AntlrGDo; -import org.scribble.parser.scribble.ast.global.AntlrGInteractionSequence; -import org.scribble.parser.scribble.ast.global.AntlrGMessageTransfer; -import org.scribble.parser.scribble.ast.global.AntlrGProtocolBlock; -import org.scribble.parser.scribble.ast.global.AntlrGProtocolDecl; -import org.scribble.parser.scribble.ast.global.AntlrGProtocolDefinition; -import org.scribble.parser.scribble.ast.global.AntlrGProtocolHeader; -import org.scribble.parser.scribble.ast.global.AntlrGRecursion; -import org.scribble.parser.scribble.ast.global.AntlrGWrap; -import org.scribble.util.ScribParserException; - -// ANTLR CommonTree -> ScribNode -// Parses ANTLR nodes into ScribNodes using the parser.ast.Antlr[...] helper classes -public class AntlrToScribParser -{ - public AntlrToScribParser() - { - - } - - public ScribNode parse(CommonTree ct, AstFactory af) throws ScribParserException - { - AntlrToScribParser.checkForAntlrErrors(ct); - - AntlrNodeType type = AntlrToScribParserUtil.getAntlrNodeType(ct); - switch (type) - { - case PAYLOAD: return AntlrPayloadElemList.parsePayloadElemList(this, ct, af); - - case MODULE: return AntlrModule.parseModule(this, ct, af); - case MODULEDECL: return AntlrModuleDecl.parseModuleDecl(this, ct, af); - case MESSAGESIGNATUREDECL: return AntlrMessageSigDecl.parseMessageSigDecl(this, ct, af); - case PAYLOADTYPEDECL: return AntlrDataTypeDecl.parseDataTypeDecl(this, ct, af); - case IMPORTMODULE: return AntlrImportModule.parseImportModule(this, ct, af); - case GLOBALPROTOCOLDECL: return AntlrGProtocolDecl.parseGPrototocolDecl(this, ct, af); - case ROLEDECLLIST: return AntlrRoleDeclList.parseRoleDeclList(this, ct, af); - case ROLEDECL: return AntlrRoleDecl.parseRoleDecl(this, ct, af); - //case CONNECTDECL: return AntlrConnectDecl.parseConnectDecl(this, ct); - case PARAMETERDECLLIST: - //case EMPTY_PARAMETERDECLLST: - return AntlrNonRoleParamDeclList.parseNonRoleParamDeclList(this, ct, af); - case PARAMETERDECL: return AntlrNonRoleParamDecl.parseNonRoleParamDecl(this, ct, af); - case ROLEINSTANTIATIONLIST: return AntlrRoleArgList.parseRoleArgList(this, ct, af); - case ROLEINSTANTIATION: return AntlrRoleArg.parseRoleArg(this, ct, af); - case ARGUMENTINSTANTIATIONLIST: return AntlrNonRoleArgList.parseNonRoleArgList(this, ct, af); - - case GLOBALPROTOCOLHEADER: return AntlrGProtocolHeader.parseGProtocolHeader(this, ct, af); - case GLOBALPROTOCOLDEF: return AntlrGProtocolDefinition.parseGProtocolDefinition(this, ct, af); - case GLOBALPROTOCOLBLOCK: return AntlrGProtocolBlock.parseGProtocolBlock(this, ct, af); - case GLOBALINTERACTIONSEQUENCE: return AntlrGInteractionSequence.parseGInteractionSequence(this, ct, af); - case MESSAGESIGNATURE: return AntlrMessageSig.parseMessageSig(this, ct, af); - case GLOBALCONNECT: return AntlrGConnect.parseGConnect(this, ct, af); - case GLOBALDISCONNECT: return AntlrGDisconnect.parseGDisconnect(this, ct, af); - case GLOBALMESSAGETRANSFER: return AntlrGMessageTransfer.parseGMessageTransfer(this, ct, af); - case GLOBALCHOICE: return AntlrGChoice.parseGChoice(this, ct, af); - case GLOBALRECURSION: return AntlrGRecursion.parseGRecursion(this, ct, af); - case GLOBALCONTINUE: return AntlrGContinue.parseGContinue(this, ct, af); - /*case GLOBALPARALLEL: return AntlrGParallel.parseGParallel(this, ct, af); - case GLOBALINTERRUPTIBLE: return AntlrGInterruptible.parseGInterruptible(this, ct, af); - case GLOBALINTERRUPT: return AntlrGInterrupt.parseGInterrupt(this, ct, af);*/ - case GLOBALDO: return AntlrGDo.parseGDo(this, ct, af); - case GLOBALWRAP: return AntlrGWrap.parseGWrap(this, ct, af); - default: throw new RuntimeException("Unknown ANTLR node type: " + type); - } - } - - public static void checkForAntlrErrors(CommonTree ct) - { - if (ct.getChildCount() > 0) // getChildren returns null instead of empty list - { - List errors = ((List) ct.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 - { - //throw new ScribParserException("Parsing errors: " + errors); // FIXME: improve feedback message - System.err.println("[ScribParser] Aborting due to parsing errors: " + errors); - System.exit(1); - } - } - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/AntlrToScribParserUtil.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/AntlrToScribParserUtil.java deleted file mode 100644 index 456d8d865..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/AntlrToScribParserUtil.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble; - -import java.util.List; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.parser.scribble.ScribbleAntlrConstants.AntlrNodeType; - -public class AntlrToScribParserUtil -{ - public static List toCommonTreeList(List list) - { - return list.stream().map((x) -> (CommonTree) x).collect(Collectors.toList()); - } - - // Cf. Scribble.g output "node types" -- mapping to the AntlrNodeType enum - public static AntlrNodeType getAntlrNodeType(CommonTree ct) - { - String type = ct.getToken().getText(); - switch (type) - { - ////case AntlrConstants.EMPTY_PARAMETERDECLLST_NODE_TYPE: return AntlrNodeType.EMPTY_PARAMETERDECLLST; - case ScribbleAntlrConstants.AMBIGUOUSNAME_NODE_TYPE: return AntlrNodeType.AMBIGUOUSNAME; - case ScribbleAntlrConstants.QUALIFIEDNAME_NODE_TYPE: return AntlrNodeType.QUALIFIEDNAME; - - case ScribbleAntlrConstants.MESSAGESIGNATURE_NODE_TYPE: return AntlrNodeType.MESSAGESIGNATURE; - case ScribbleAntlrConstants.DELEGATION_NODE_TYPE: return AntlrNodeType.DELEGATION; - - case ScribbleAntlrConstants.PAYLOAD_NODE_TYPE: return AntlrNodeType.PAYLOAD; - //case AntlrConstants.PAYLOADELEMENT_NODE_TYPE: return AntlrNodeType.PAYLOADELEMENT; - - case ScribbleAntlrConstants.MODULE_NODE_TYPE: return AntlrNodeType.MODULE; - case ScribbleAntlrConstants.MODULEDECL_NODE_TYPE: return AntlrNodeType.MODULEDECL; - case ScribbleAntlrConstants.IMPORTMODULE_NODE_TYPE: return AntlrNodeType.IMPORTMODULE; - case ScribbleAntlrConstants.IMPORTMEMBER_NODE_TYPE: return AntlrNodeType.IMPORTMEMBER; - case ScribbleAntlrConstants.PAYLOADTYPEDECL_NODE_TYPE: return AntlrNodeType.PAYLOADTYPEDECL; - case ScribbleAntlrConstants.MESSAGESIGNATUREDECL_NODE_TYPE: return AntlrNodeType.MESSAGESIGNATUREDECL; - case ScribbleAntlrConstants.ROLEDECLLIST_NODE_TYPE: return AntlrNodeType.ROLEDECLLIST; - case ScribbleAntlrConstants.ROLEDECL_NODE_TYPE: return AntlrNodeType.ROLEDECL; - case ScribbleAntlrConstants.PARAMETERDECLLIST_NODE_TYPE: return AntlrNodeType.PARAMETERDECLLIST; - case ScribbleAntlrConstants.PARAMETERDECL_NODE_TYPE: return AntlrNodeType.PARAMETERDECL; - case ScribbleAntlrConstants.ROLEINSTANTIATIONLIST_NODE_TYPE: return AntlrNodeType.ROLEINSTANTIATIONLIST; - case ScribbleAntlrConstants.ROLEINSTANTIATION_NODE_TYPE: return AntlrNodeType.ROLEINSTANTIATION; - case ScribbleAntlrConstants.ARGUMENTINSTANTIATIONLIST_NODE_TYPE: return AntlrNodeType.ARGUMENTINSTANTIATIONLIST; - //case ScribbleAntlrConstants.ARGUMENTINSTANTIATION_NODE_TYPE: return AntlrNodeType.ARGUMENTINSTANTIATION; // Not used directly? - - case ScribbleAntlrConstants.GLOBALPROTOCOLDECL_NODE_TYPE: return AntlrNodeType.GLOBALPROTOCOLDECL; - case ScribbleAntlrConstants.GLOBALPROTOCOLHEADER_NODE_TYPE: return AntlrNodeType.GLOBALPROTOCOLHEADER; - case ScribbleAntlrConstants.GLOBALPROTOCOLDEF_NODE_TYPE: return AntlrNodeType.GLOBALPROTOCOLDEF; - case ScribbleAntlrConstants.GLOBALPROTOCOLBLOCK_NODE_TYPE: return AntlrNodeType.GLOBALPROTOCOLBLOCK; - case ScribbleAntlrConstants.GLOBALINTERACTIONSEQUENCE_NODE_TYPE: return AntlrNodeType.GLOBALINTERACTIONSEQUENCE; - case ScribbleAntlrConstants.GLOBALMESSAGETRANSFER_NODE_TYPE: return AntlrNodeType.GLOBALMESSAGETRANSFER; - case ScribbleAntlrConstants.GLOBALCONNECT_NODE_TYPE: return AntlrNodeType.GLOBALCONNECT; - case ScribbleAntlrConstants.GLOBALWRAP_NODE_TYPE: return AntlrNodeType.GLOBALWRAP; - case ScribbleAntlrConstants.GLOBALDISCONNECT_NODE_TYPE: return AntlrNodeType.GLOBALDISCONNECT; - case ScribbleAntlrConstants.GLOBALCHOICE_NODE_TYPE: return AntlrNodeType.GLOBALCHOICE; - case ScribbleAntlrConstants.GLOBALRECURSION_NODE_TYPE: return AntlrNodeType.GLOBALRECURSION; - case ScribbleAntlrConstants.GLOBALCONTINUE_NODE_TYPE: return AntlrNodeType.GLOBALCONTINUE; - /*case ScribbleAntlrConstants.GLOBALPARALLEL_NODE_TYPE: return AntlrNodeType.GLOBALPARALLEL; - case ScribbleAntlrConstants.GLOBALINTERRUPTIBLE_NODE_TYPE: return AntlrNodeType.GLOBALINTERRUPTIBLE; - case ScribbleAntlrConstants.GLOBALINTERRUPT_NODE_TYPE: return AntlrNodeType.GLOBALINTERRUPT;*/ - case ScribbleAntlrConstants.GLOBALDO_NODE_TYPE: return AntlrNodeType.GLOBALDO; - - /*case ScribbleAntlrConstants.LOCALPROTOCOLDECL_NODE_TYPE: return AntlrNodeType.LOCALPROTOCOLDECL; - case ScribbleAntlrConstants.LOCALROLEDECLLIST_NODE_TYPE: return AntlrNodeType.ROLEDECLLIST; - case ScribbleAntlrConstants.LOCALROLEDECL_NODE_TYPE: return AntlrNodeType.ROLEDECL; - case ScribbleAntlrConstants.SELFDECL_NODE_TYPE: return AntlrNodeType.SELFDECL; - case ScribbleAntlrConstants.LOCALPROTOCOLDEF_NODE_TYPE: return AntlrNodeType.LOCALPROTOCOLDEF; - case ScribbleAntlrConstants.LOCALPROTOCOLBLOCK_NODE_TYPE: return AntlrNodeType.LOCALPROTOCOLBLOCK; - case ScribbleAntlrConstants.LOCALINTERACTIONSEQUENCE_NODE_TYPE: return AntlrNodeType.LOCALINTERACTIONSEQUENCE; - case ScribbleAntlrConstants.LOCALSEND_NODE_TYPE: return AntlrNodeType.LOCALSEND; - case ScribbleAntlrConstants.LOCALRECEIVE_NODE_TYPE: return AntlrNodeType.LOCALRECEIVE; - case ScribbleAntlrConstants.LOCALCHOICE_NODE_TYPE: return AntlrNodeType.LOCALCHOICE; - case ScribbleAntlrConstants.LOCALRECURSION_NODE_TYPE: return AntlrNodeType.LOCALRECURSION; - case ScribbleAntlrConstants.LOCALCONTINUE_NODE_TYPE: return AntlrNodeType.LOCALCONTINUE; - case ScribbleAntlrConstants.LOCALPARALLEL_NODE_TYPE: return AntlrNodeType.LOCALPARALLEL; - case ScribbleAntlrConstants.LOCALINTERRUPTIBLE_NODE_TYPE: return AntlrNodeType.LOCALINTERRUPTIBLE; - case ScribbleAntlrConstants.LOCALTHROWS_NODE_TYPE: return AntlrNodeType.LOCALTHROWS; - case ScribbleAntlrConstants.LOCALCATCHES_NODE_TYPE: return AntlrNodeType.LOCALCATCHES; - case ScribbleAntlrConstants.LOCALDO_NODE_TYPE: return AntlrNodeType.LOCALDO;*/ - - // Nodes without a "node type", e.g. parameter names, fall in here - default: throw new RuntimeException("Unknown ANTLR node type label: " + type); - } - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ScribModuleLoader.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ScribModuleLoader.java deleted file mode 100644 index 31cdcc888..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ScribModuleLoader.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble; - -import org.scribble.ast.AstFactory; -import org.scribble.ast.Module; -import org.scribble.main.DefaultModuleLoader; -import org.scribble.main.ScribbleException; -import org.scribble.main.resource.Resource; -import org.scribble.main.resource.ResourceLocator; -import org.scribble.type.name.ModuleName; -import org.scribble.util.Pair; -import org.scribble.util.ScribParserException; - -// loading = ModuleName -> Module -// ModuleName --> Path --ResourceLocator--> Resource --AntlrParser--> ANTLR --ScribParser--> ScribNode -// FIXME: should be in core org.scribble.main -- here due to Maven dependency restrictions -public class ScribModuleLoader extends DefaultModuleLoader //implements ModuleLoader -{ - private ResourceLocator locator; - private ScribbleAntlrWrapper antlr; - private AntlrToScribParser parser; - - public ScribModuleLoader(ResourceLocator locator, ScribbleAntlrWrapper antlr, AntlrToScribParser parser) - { - this.locator = locator; - this.antlr = antlr; - this.parser = parser; - } - - @Override - public Pair loadModule(ModuleName modname, AstFactory af) throws ScribParserException, ScribbleException - { - Pair cached = super.loadModule(modname, af); - if (cached != null) - { - return cached; - } - Resource res = this.locator.getResource(modname.toPath()); - Module parsed = (Module) this.parser.parse(this.antlr.parseAntlrTree(res), af); - checkModuleName(modname, res, parsed); - registerModule(res, parsed); - return new Pair<>(res, parsed); - } - - private static void checkModuleName(ModuleName mn, Resource res, Module mod) - { - if (!mn.equals(mod.getFullModuleName())) - { - throw new RuntimeException("Invalid module name " + mod.getFullModuleName() + " at location: " + res.getLocation()); - } - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ScribbleAntlrConstants.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ScribbleAntlrConstants.java deleted file mode 100644 index 47444f361..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ScribbleAntlrConstants.java +++ /dev/null @@ -1,198 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble; - -// Constants declared in Scribble.g ANTLR grammer -public class ScribbleAntlrConstants -{ - /** - * Cf. Scribble.g, parser output "node types" - */ - - // Parsed "indirectly" -- i.e., not as explicit cases in AntlrToScribParser::parse - - public static final String EMPTY_ALIAS = "EMPTY_ALIAS"; - public static final String ANTLR_EMPTY_OPERATOR = "EMPTY_OPERATOR"; - //public static final String ANTLR_NO_SCOPE = "NO_SCOPE"; - - public static final String KIND_MESSAGESIGNATURE = "KIND_MESSAGESIGNATURE"; - public static final String KIND_PAYLOADTYPE = "KIND_PAYLOADTYPE"; - - ////public static final String EMPTY_PARAMETERDECLLST_NODE_TYPE = "EMPTY_PARAMETERDECLLIST"; - public static final String AMBIGUOUSNAME_NODE_TYPE = "AMBIGUOUSNAME"; - public static final String QUALIFIEDNAME_NODE_TYPE = "QUALIFIEDNAME"; - - public static final String MESSAGESIGNATURE_NODE_TYPE = "MESSAGESIGNATURE"; - public static final String DELEGATION_NODE_TYPE = "DELEGATION"; - - - // Parsed "directly" by AntlrToScribParser::parse - - public static final String PAYLOAD_NODE_TYPE = "PAYLOAD"; - //public static final String PAYLOADELEMENT_NODE_TYPE = "PAYLOADELEMENT"; - - public static final String MODULE_NODE_TYPE = "MODULE"; - public static final String MODULEDECL_NODE_TYPE = "MODULEDECL"; - public static final String IMPORTMODULE_NODE_TYPE = "IMPORTMODULE"; - public static final String IMPORTMEMBER_NODE_TYPE = "IMPORTMEMBER"; - public static final String PAYLOADTYPEDECL_NODE_TYPE = "PAYLOADTYPEDECL"; - public static final String MESSAGESIGNATUREDECL_NODE_TYPE = "MESSAGESIGNATUREDECL"; - public static final String ROLEDECLLIST_NODE_TYPE = "ROLEDECLLIST"; - public static final String ROLEDECL_NODE_TYPE = "ROLEDECL"; - public static final String PARAMETERDECLLIST_NODE_TYPE = "PARAMETERDECLLIST"; - public static final String PARAMETERDECL_NODE_TYPE = "PARAMETERDECL"; - public static final String ROLEINSTANTIATIONLIST_NODE_TYPE = "ROLEINSTANTIATIONLIST"; - public static final String ROLEINSTANTIATION_NODE_TYPE = "ROLEINSTANTIATION"; - public static final String ARGUMENTINSTANTIATIONLIST_NODE_TYPE = "ARGUMENTINSTANTIATIONLIST"; - public static final String ARGUMENTINSTANTIATION_NODE_TYPE = "ARGUMENTINSTANTIATION"; - - public static final String GLOBALPROTOCOLDECL_NODE_TYPE = "GLOBALPROTOCOLDECL"; - public static final String GLOBALPROTOCOLHEADER_NODE_TYPE = "GLOBALPROTOCOLHEADER"; - public static final String GLOBALPROTOCOLDEF_NODE_TYPE = "GLOBALPROTOCOLDEF"; - public static final String GLOBALPROTOCOLBLOCK_NODE_TYPE = "GLOBALPROTOCOLBLOCK"; - public static final String GLOBALINTERACTIONSEQUENCE_NODE_TYPE = "GLOBALINTERACTIONSEQUENCE"; - public static final String GLOBALMESSAGETRANSFER_NODE_TYPE = "GLOBALMESSAGETRANSFER"; - public static final String GLOBALCONNECT_NODE_TYPE = "GLOBALCONNECT"; - public static final String GLOBALDISCONNECT_NODE_TYPE = "GLOBALDISCONNECT"; - public static final String GLOBALWRAP_NODE_TYPE = "GLOBALWRAP"; - public static final String GLOBALCHOICE_NODE_TYPE = "GLOBALCHOICE"; - public static final String GLOBALRECURSION_NODE_TYPE = "GLOBALRECURSION"; - public static final String GLOBALCONTINUE_NODE_TYPE = "GLOBALCONTINUE"; - /*public static final String GLOBALPARALLEL_NODE_TYPE = "GLOBALPARALLEL"; - public static final String GLOBALINTERRUPTIBLE_NODE_TYPE = "GLOBALINTERRUPTIBLE"; - public static final String GLOBALINTERRUPT_NODE_TYPE = "GLOBALINTERRUPT";*/ - public static final String GLOBALDO_NODE_TYPE = "GLOBALDO"; - - - //FIXME: local nodes are currently not ANTLR nodes -- locals only projected, not parsed - - public static final String LOCALPROTOCOLDECL_NODE_TYPE = "LOCALPROTOCOLDECL"; - /*public static final String LOCALROLEDECLLIST_NODE_TYPE = "LOCALROLEDECLLIST"; - public static final String LOCALROLEDECL_NODE_TYPE = "LOCALROLEDECL"; - public static final String SELFDECL_NODE_TYPE = "SELFDECL"; - public static final String LOCALPROTOCOLDEF_NODE_TYPE = "LOCALPROTOCOLDEF"; - public static final String LOCALPROTOCOLBLOCK_NODE_TYPE = "LOCALPROTOCOLBLOCK"; - public static final String LOCALINTERACTIONSEQUENCE_NODE_TYPE = "LOCALINTERACTIONSEQUENCE"; - public static final String LOCALSEND_NODE_TYPE = "LOCALSEND"; - public static final String LOCALRECEIVE_NODE_TYPE = "LOCALRECEIVE"; - public static final String LOCALCHOICE_NODE_TYPE = "LOCALCHOICE"; - public static final String LOCALRECURSION_NODE_TYPE = "LOCALRECURSION"; - public static final String LOCALCONTINUE_NODE_TYPE = "LOCALCONTINUE"; - public static final String LOCALPARALLEL_NODE_TYPE = "LOCALPARALLEL"; - public static final String LOCALINTERRUPTIBLE_NODE_TYPE = "LOCALINTERRUPTIBLE"; - public static final String LOCALTHROWS_NODE_TYPE = "LOCALTHROWS"; - public static final String LOCALCATCHES_NODE_TYPE = "LOCALCATCHES"; - public static final String LOCALDO_NODE_TYPE = "LOCALDO";*/ - - - // Scribble.g, parser output "node types" as a Java enum - public enum AntlrNodeType - { - //EMPTY_PARAMETERDECLLST, - AMBIGUOUSNAME, - QUALIFIEDNAME, - - MESSAGESIGNATURE, - DELEGATION, - - PAYLOAD, - //PAYLOADELEMENT, - - MODULE, - MODULEDECL, - IMPORTMODULE, - IMPORTMEMBER, - PAYLOADTYPEDECL, - MESSAGESIGNATUREDECL, - ROLEDECLLIST, - ROLEDECL, - //CONNECTDECL, - PARAMETERDECLLIST, - PARAMETERDECL, - ROLEINSTANTIATIONLIST, - ROLEINSTANTIATION, - ARGUMENTINSTANTIATIONLIST, - ARGUMENTINSTANTIATION, - - GLOBALPROTOCOLDECL, - GLOBALPROTOCOLHEADER, - GLOBALPROTOCOLDEF, - GLOBALPROTOCOLBLOCK, - GLOBALINTERACTIONSEQUENCE, - GLOBALMESSAGETRANSFER, - GLOBALCONNECT, - GLOBALDISCONNECT, - GLOBALWRAP, - GLOBALCHOICE, - GLOBALRECURSION, - GLOBALCONTINUE, - /*GLOBALPARALLEL, - GLOBALINTERRUPTIBLE, - GLOBALINTERRUPT,*/ - GLOBALDO, - - LOCALPROTOCOLDECL, - /*LOCALROLEDECLLIST, - LOCALROLEDECL, - SELFDECL, - LOCALPROTOCOLDEF, - LOCALPROTOCOLBLOCK, - LOCALINTERACTIONSEQUENCE, - LOCALSEND, - LOCALRECEIVE, - LOCALCHOICE, - LOCALRECURSION, - LOCALCONTINUE, - LOCALPARALLEL, - LOCALINTERRUPTIBLE, - LOCALTHROWS, - LOCALCATCHES, - LOCALDO*/ - } - - - // Duplicated from Scribble.g (parser input constants) -- what's the best way to share it? - // Mostly used in projection (outputting local types) - // FIXME: refer to core ast Constants? Cannot refer the other way around due to Maven dependencies - public static final String MODULE_KW = "module"; - public static final String IMPORT_KW = "import"; - public static final String TYPE_KW = "type"; - 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 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 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"; -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ScribbleAntlrWrapper.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ScribbleAntlrWrapper.java deleted file mode 100644 index 2a2a8a159..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ScribbleAntlrWrapper.java +++ /dev/null @@ -1,132 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble; - -import java.io.IOException; -import java.io.InputStream; - -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.CommonTree; -import org.scribble.main.resource.Resource; -import org.scribble.parser.antlr.ScribbleLexer; -import org.scribble.parser.antlr.ScribbleParser; - -// Resource -> ANTLR CommonTree -- parses Resources into ANTLR CommonTrees -// Wraps the ScribbleLexer and ScribbleParser generated by ANTLR from Scribble.g -// Not encapsulated inside ScribParser, because ScribParser's main function is the higher-level operation of "parsing" CommonTrees into ScribNodes -public class ScribbleAntlrWrapper -{ - public ScribbleAntlrWrapper() - { - - } - - // Scribble extensions should override these "new" methods - protected Lexer getScribbleLexer(ANTLRStringStream ass) - { - return new ScribbleLexer(ass); - } - - /*protected Parser newScribbleParser(CommonTokenStream cts) - { - return new ScribbleParser(cts); - }*/ - protected CommonTree runScribbleParser(CommonTokenStream cts) throws RecognitionException - { - // Because no convenient way to expose an interface for all ScribbleParsers with top-level "module" method? - return (CommonTree) new ScribbleParser(cts).module().getTree(); - } - - public CommonTree parseAntlrTree(Resource res) - { - try - { - String input = readInput(res); - Lexer lex = getScribbleLexer(new ANTLRStringStream(input)); - //Parser parser = newScribbleParser(new CommonTokenStream(lex)); - ////return (CommonTree) parser.module().getTree(); - - /*Class c = parser.getClass(); - try*/ - { - /*// FIXME: need an interface for Scribble top-level module method (ANTLR "grammar actions"?) - Method m = c.getMethod("module"); - return (CommonTree) ((ParserRuleReturnScope) m.invoke(parser)).getTree();*/ // No: reflection doesn't work well with ANTLR error handling - - return runScribbleParser(new CommonTokenStream(lex)); - } - /*catch (NoSuchMethodException nsme) - { - throw new RuntimeException("Supplied Parser has no \"module\" method.", nsme); - } - catch (IllegalAccessException e) - { - throw new RuntimeException("Shouldn't get in here: ", e); - } - catch (IllegalArgumentException e) - { - throw new RuntimeException("Shouldn't get in here: ", e); - } - catch (InvocationTargetException e) - { - if (e.getCause() instanceof RecognitionException) - { - throw new RuntimeException(e); - } - throw new RuntimeException("Shouldn't get in here: ", e); - }*/ - } - catch (RecognitionException e) - { - throw new RuntimeException(e); - } - } - - /*public CommonTree parseAntlrTree(Resource res) - { - try - { - String input = readInput(res); - ScribbleLexer lex = new ScribbleLexer(new ANTLRStringStream(input)); - ScribbleParser parser = new ScribbleParser(new CommonTokenStream(lex)); - return (CommonTree) parser.module().getTree(); - } - catch (RecognitionException e) - { - throw new RuntimeException(e); - } - }*/ - - protected static String readInput(Resource res) - { - return new String(readResource(res)); - } - - private static byte[] readResource(Resource res) - { - try (InputStream is = res.getInputStream()) - { - byte[] bs = new byte[is.available()]; - is.read(bs); - return bs; - } - catch (IOException e) - { - throw new RuntimeException(e); - } - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrDataTypeDecl.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrDataTypeDecl.java deleted file mode 100644 index ee97f1456..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrDataTypeDecl.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.DataTypeDecl; -import org.scribble.ast.name.qualified.DataTypeNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; - -public class AntlrDataTypeDecl -{ - public static final int SCHEMA_CHILD_INDEX = 0; - public static final int EXTNAME_CHILD_INDEX = 1; - public static final int SOURCE_CHILD_INDEX = 2; - public static final int ALIAS_CHILD_INDEX = 3; - - public static DataTypeDecl parseDataTypeDecl(AntlrToScribParser parser, CommonTree ct, AstFactory af) - { - CommonTree tmp1 = getSchemaChild(ct); - String schema = AntlrSimpleName.getName(tmp1); - CommonTree tmp2 = getExtNameChild(ct); - String extName = AntlrExtIdentifier.getName(tmp2); - CommonTree tmp3 = getSourceChild(ct); - String source = AntlrExtIdentifier.getName(tmp3); - DataTypeNode alias = AntlrSimpleName.toDataTypeNameNode(getAliasChild(ct), af); // FIXME: EMTPY_ALIAS? - return af.DataTypeDecl(ct, schema, extName, source, alias); - } - - public static CommonTree getSchemaChild(CommonTree ct) - { - return (CommonTree) ct.getChild(SCHEMA_CHILD_INDEX); - } - - public static CommonTree getExtNameChild(CommonTree ct) - { - return (CommonTree) ct.getChild(EXTNAME_CHILD_INDEX); - } - - public static CommonTree getSourceChild(CommonTree ct) - { - return (CommonTree) ct.getChild(SOURCE_CHILD_INDEX); - } - - public static CommonTree getAliasChild(CommonTree ct) - { - return (CommonTree) ct.getChild(ALIAS_CHILD_INDEX); - } - - public static CommonTree getModuleParent(CommonTree ct) - { - return (CommonTree) ct.getParent(); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrExtIdentifier.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrExtIdentifier.java deleted file mode 100644 index a36ccc0d8..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrExtIdentifier.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast; - -import org.antlr.runtime.tree.CommonTree; - -public class AntlrExtIdentifier -{ - public static final String getName(CommonTree ct) - { - String text = ct.getText(); - return text.substring(1, text.length() - 1); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrImportModule.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrImportModule.java deleted file mode 100644 index 3ed0c6465..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrImportModule.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.ImportModule; -import org.scribble.ast.name.qualified.ModuleNameNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.ScribbleAntlrConstants; -import org.scribble.parser.scribble.ast.name.AntlrQualifiedName; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; - -public class AntlrImportModule -{ - public static final int MODULENAME_CHILD_INDEX = 0; - public static final int ALIAS_CHILD_INDEX = 1; - - public static ImportModule parseImportModule(AntlrToScribParser parser, CommonTree ct, AstFactory af) - { - ModuleNameNode fmn = AntlrQualifiedName.toModuleNameNode(getModuleNameChild(ct), af); - ModuleNameNode alias = (hasAlias(ct)) - ? AntlrSimpleName.toModuleNameNode(getAliasChild(ct), af) - : null; - return af.ImportModule(ct, fmn, alias); - } - - public static CommonTree getModuleNameChild(CommonTree ct) - { - return (CommonTree) ct.getChild(MODULENAME_CHILD_INDEX); - } - - public static CommonTree getAliasChild(CommonTree ct) - { - return (CommonTree) ct.getChild(ALIAS_CHILD_INDEX); - } - - public static boolean hasAlias(CommonTree ct) - { - return !ct.getChild(ALIAS_CHILD_INDEX).getText().equals(ScribbleAntlrConstants.EMPTY_ALIAS); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrMessageSig.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrMessageSig.java deleted file mode 100644 index 1e842ca4a..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrMessageSig.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.MessageSigNode; -import org.scribble.ast.PayloadElemList; -import org.scribble.ast.name.simple.OpNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; -import org.scribble.util.ScribParserException; - -public class AntlrMessageSig -{ - public static final int OPERATOR_CHILD_INDEX = 0; - public static final int PAYLOAD_CHILD_INDEX = 1; - - public static MessageSigNode parseMessageSig(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - OpNode op = AntlrSimpleName.toOpNode(getOpChild(ct), af); - PayloadElemList payload = (PayloadElemList) parser.parse(getPayloadElemListChild(ct), af); - return af.MessageSigNode(ct, op, payload); - } - - public static CommonTree getOpChild(CommonTree ct) - { - return (CommonTree) ct.getChild(OPERATOR_CHILD_INDEX); - } - - public static CommonTree getPayloadElemListChild(CommonTree ct) - { - return (CommonTree) ct.getChild(PAYLOAD_CHILD_INDEX); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrMessageSigDecl.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrMessageSigDecl.java deleted file mode 100644 index 12bdc6da1..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrMessageSigDecl.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.MessageSigNameDecl; -import org.scribble.ast.name.qualified.MessageSigNameNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; - -// FIXME: factor out with AntlrDataTypeDecl -public class AntlrMessageSigDecl -{ - public static final int SCHEMA_CHILD_INDEX = 0; - public static final int EXTNAME_CHILD_INDEX = 1; - public static final int SOURCE_CHILD_INDEX = 2; - public static final int ALIAS_CHILD_INDEX = 3; - - public static MessageSigNameDecl parseMessageSigDecl(AntlrToScribParser parser, CommonTree ct, AstFactory af) - { - CommonTree tmp1 = getSchemaChild(ct); - String schema = AntlrSimpleName.getName(tmp1); - CommonTree tmp2 = getExtNameChild(ct); - String extName = AntlrExtIdentifier.getName(tmp2); - CommonTree tmp3 = getSourceChild(ct); - String source = AntlrExtIdentifier.getName(tmp3); - MessageSigNameNode alias = AntlrSimpleName.toMessageSigNameNode(getAliasChild(ct), af); - return af.MessageSigNameDecl(ct, schema, extName, source, alias); - } - - public static CommonTree getSchemaChild(CommonTree ct) - { - return (CommonTree) ct.getChild(SCHEMA_CHILD_INDEX); - } - - public static CommonTree getExtNameChild(CommonTree ct) - { - return (CommonTree) ct.getChild(EXTNAME_CHILD_INDEX); - } - - public static CommonTree getSourceChild(CommonTree ct) - { - return (CommonTree) ct.getChild(SOURCE_CHILD_INDEX); - } - - public static CommonTree getAliasChild(CommonTree ct) - { - return (CommonTree) ct.getChild(ALIAS_CHILD_INDEX); - } - - public static CommonTree getModuleParent(CommonTree ct) - { - return (CommonTree) ct.getParent(); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrModule.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrModule.java deleted file mode 100644 index 471e9b9a6..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrModule.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.ImportDecl; -import org.scribble.ast.Module; -import org.scribble.ast.ModuleDecl; -import org.scribble.ast.NonProtocolDecl; -import org.scribble.ast.ProtocolDecl; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.AntlrToScribParserUtil; -import org.scribble.parser.scribble.ScribbleAntlrConstants.AntlrNodeType; -import org.scribble.util.ScribParserException; - -public class AntlrModule -{ - public static final int MODULEDECL_CHILD_INDEX = 0; - - public static Module parseModule(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - ModuleDecl md = (ModuleDecl) parser.parse(getModuleDeclChild(ct), af); - List> ids = new LinkedList<>(); - List> ptds = new LinkedList<>(); - List> pds = new LinkedList<>(); - for (CommonTree id : getImportDeclChildren(ct)) - { - ImportDecl tmp = (ImportDecl) parser.parse(id, af); - ids.add(tmp); - } - for (CommonTree ptd : getDataTypeDeclChildren(ct)) - { - NonProtocolDecl tmp = (NonProtocolDecl) parser.parse(ptd, af); - ptds.add(tmp); - } - for (CommonTree pd : getProtocolDeclChildren(ct)) - { - ProtocolDecl tmp = (ProtocolDecl) parser.parse(pd, af); - pds.add(tmp); - } - return af.Module(ct, md, ids, ptds, pds); - } - - public static CommonTree getModuleDeclChild(CommonTree ct) - { - return (CommonTree) ct.getChild(MODULEDECL_CHILD_INDEX); - } - - public static List getImportDeclChildren(CommonTree ct) - { - return filterChildren(ct, AntlrNodeType.IMPORTMODULE, AntlrNodeType.IMPORTMEMBER); - } - - public static List getDataTypeDeclChildren(CommonTree ct) - { - return filterChildren(ct, AntlrNodeType.PAYLOADTYPEDECL, AntlrNodeType.MESSAGESIGNATUREDECL); - } - - public static List getProtocolDeclChildren(CommonTree ct) - { - return filterChildren(ct, AntlrNodeType.GLOBALPROTOCOLDECL, AntlrNodeType.LOCALPROTOCOLDECL); - } - - private static List filterChildren(CommonTree ct, AntlrNodeType... types) - { - List tmp = Arrays.asList(types); - List children = AntlrToScribParserUtil.toCommonTreeList(ct.getChildren()); - return children.subList(1, children.size()).stream() - .filter((c) -> tmp.contains(AntlrToScribParserUtil.getAntlrNodeType(c))).collect(Collectors.toList()); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrModuleDecl.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrModuleDecl.java deleted file mode 100644 index dcc769ffd..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrModuleDecl.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.ModuleDecl; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.ast.name.AntlrQualifiedName; - -public class AntlrModuleDecl -{ - public static final int MODULENAME_CHILD_INDEX = 0; - - public static ModuleDecl parseModuleDecl(AntlrToScribParser parser, CommonTree ct, AstFactory af) - { - return af.ModuleDecl(ct, AntlrQualifiedName.toModuleNameNode(getModuleNameChild(ct), af)); - } - - public static CommonTree getModuleNameChild(CommonTree ct) - { - return (CommonTree) ct.getChild(MODULENAME_CHILD_INDEX); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrNonRoleArgList.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrNonRoleArgList.java deleted file mode 100644 index 5af278272..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrNonRoleArgList.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.NonRoleArg; -import org.scribble.ast.NonRoleArgList; -import org.scribble.ast.NonRoleArgNode; -import org.scribble.ast.name.qualified.DataTypeNode; -import org.scribble.ast.name.simple.AmbigNameNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.AntlrToScribParserUtil; -import org.scribble.parser.scribble.ScribbleAntlrConstants.AntlrNodeType; -import org.scribble.parser.scribble.ast.name.AntlrAmbigName; -import org.scribble.parser.scribble.ast.name.AntlrQualifiedName; -import org.scribble.util.ScribParserException; - -public class AntlrNonRoleArgList -{ - // Similar to AntlrPayloadElemList - public static NonRoleArgList parseNonRoleArgList(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - //List as = getArgumentChildren(ct).stream().map((a) -> parseNonRoleArg(parser, a)).collect(Collectors.toList()); - List as = new LinkedList<>(); - for (CommonTree a : getArgumentChildren(ct)) - { - as.add(parseNonRoleArg(parser, a, af)); - } - return af.NonRoleArgList(ct, as); - } - - // Not in own class because not called by ScribbleParser -- called directly from above - private static NonRoleArg parseNonRoleArg(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - AntlrNodeType type = AntlrToScribParserUtil.getAntlrNodeType(ct); - if (type == AntlrNodeType.MESSAGESIGNATURE) - { - NonRoleArgNode arg = (NonRoleArgNode) parser.parse(ct, af); - return af.NonRoleArg(ct, arg); - } - else - { - /* // Parser isn't working to distinguish simple from qualified names (similarly to PayloadElemList) - if (type == AntlrNodeType.AMBIGUOUSNAME) - { - return AstFactoryImpl.FACTORY.NonRoleArg(AntlrAmbigName.toAmbigNameNode(ct)); - } - else - { - throw new RuntimeException("Shouldn't get in here: " + type); - }*/ - if (type == AntlrNodeType.QUALIFIEDNAME) - { - if (ct.getChildCount() > 1) - { - DataTypeNode dt = AntlrQualifiedName.toDataTypeNameNode(ct, af); - return af.NonRoleArg(ct, dt); - } - else - { - // Similarly to NonRoleArg: cannot syntactically distinguish right now between SimplePayloadTypeNode and ParameterNode - AmbigNameNode an = AntlrAmbigName.toAmbigNameNode(ct, af); - return af.NonRoleArg(ct, an); - } - } - else - { - throw new RuntimeException("Shouldn't get in here: " + ct); - } - } - } - - public static List getArgumentChildren(CommonTree ct) - { - return (ct.getChildCount() == 0) - ? Collections.emptyList() - : AntlrToScribParserUtil.toCommonTreeList(ct.getChildren()); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrNonRoleParamDecl.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrNonRoleParamDecl.java deleted file mode 100644 index baad8514d..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrNonRoleParamDecl.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.NonRoleParamDecl; -import org.scribble.ast.name.simple.NonRoleParamNode; -import org.scribble.parser.scribble.ScribbleAntlrConstants; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; -import org.scribble.type.kind.DataTypeKind; -import org.scribble.type.kind.Kind; -import org.scribble.type.kind.NonRoleParamKind; -import org.scribble.type.kind.SigKind; - -public class AntlrNonRoleParamDecl -{ - public static final int KIND_CHILD_INDEX = 0; - public static final int NAME_CHILD_INDEX = 1; - - public static NonRoleParamDecl parseNonRoleParamDecl(AntlrToScribParser parser, CommonTree ct, AstFactory af) - { - Kind kind = parseKind(getKindChild(ct)); - if (kind.equals(SigKind.KIND)) - { - NonRoleParamNode name = AntlrSimpleName.toParamNode(SigKind.KIND, getNameChild(ct), af); - return af.NonRoleParamDecl(ct, SigKind.KIND, name); - } - else if (kind.equals(DataTypeKind.KIND)) - { - NonRoleParamNode name = AntlrSimpleName.toParamNode(DataTypeKind.KIND, getNameChild(ct), af); - return af.NonRoleParamDecl(ct, DataTypeKind.KIND, name); - } - else - { - throw new RuntimeException("Shouldn't get in here: " + kind); - } - } - - private static Kind parseKind(CommonTree ct) - { - String kind = ct.getText(); - switch (kind) - { - case ScribbleAntlrConstants.KIND_MESSAGESIGNATURE: - { - return SigKind.KIND; - } - case ScribbleAntlrConstants.KIND_PAYLOADTYPE: - { - return DataTypeKind.KIND; - } - default: - { - throw new RuntimeException("Unknown parameter declaration kind: " + kind); - } - } - } - - public static CommonTree getKindChild(CommonTree ct) - { - return (CommonTree) ct.getChild(KIND_CHILD_INDEX); - } - - public static CommonTree getNameChild(CommonTree ct) - { - return (CommonTree) ct.getChild(NAME_CHILD_INDEX); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrNonRoleParamDeclList.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrNonRoleParamDeclList.java deleted file mode 100644 index 0b9e75f2d..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrNonRoleParamDeclList.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.NonRoleParamDecl; -import org.scribble.ast.NonRoleParamDeclList; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.AntlrToScribParserUtil; -import org.scribble.type.kind.NonRoleParamKind; -import org.scribble.util.ScribParserException; - -public class AntlrNonRoleParamDeclList -{ - public static NonRoleParamDeclList parseNonRoleParamDeclList(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - List> pds = new LinkedList<>(); - for (CommonTree pd : getParamDeclChildren(ct)) - { - NonRoleParamDecl parsed = (NonRoleParamDecl) parser.parse(pd, af); - @SuppressWarnings("unchecked") // OK: the node is immutable -- will never "rewrite" the generic value (the kind) in it - NonRoleParamDecl tmp = (NonRoleParamDecl) parsed; - pds.add(tmp); - } - return af.NonRoleParamDeclList(ct, pds); - } - - public static final List getParamDeclChildren(CommonTree ct) - { - return (ct.getChildCount() == 0) - ? Collections.emptyList() - : AntlrToScribParserUtil.toCommonTreeList(ct.getChildren()); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrPayloadElemList.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrPayloadElemList.java deleted file mode 100644 index 6c311cb6c..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrPayloadElemList.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast; - -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.PayloadElem; -import org.scribble.ast.PayloadElemList; -import org.scribble.ast.name.qualified.DataTypeNode; -import org.scribble.ast.name.qualified.GProtocolNameNode; -import org.scribble.ast.name.simple.AmbigNameNode; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.AntlrToScribParserUtil; -import org.scribble.parser.scribble.ScribbleAntlrConstants.AntlrNodeType; -import org.scribble.parser.scribble.ast.name.AntlrAmbigName; -import org.scribble.parser.scribble.ast.name.AntlrQualifiedName; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; - -public class AntlrPayloadElemList -{ - // Cf. AntlrNonRoleArgList - public static PayloadElemList parsePayloadElemList(AntlrToScribParser parser, CommonTree ct, AstFactory af) - { - // As in AntlrNonRoleArgList, i.e. payloadelem (NonRoleArg) not directly parsed -- cf. rolearg and nonroleparamdecl, which are directly parsed (not consistent), due to amibgious names - //List pes = getPayloadElements(ct).stream().map((pe) -> parsePayloadElem(pe)).collect(Collectors.toList()); - List> pes = getPayloadElements(ct).stream().map(pe -> parsePayloadElem(pe, af)).collect(Collectors.toList()); - return af.PayloadElemList(ct, pes); - } - - //private static PayloadElem parsePayloadElem(CommonTree ct) - public static PayloadElem parsePayloadElem(CommonTree ct, AstFactory af) - { - AntlrNodeType type = AntlrToScribParserUtil.getAntlrNodeType(ct); - /*// Parser isn't working to distinguish simple from qualified names (cf. Scribble.g payloadelement) - if (type == AntlrNodeType.QUALIFIEDNAME) - { - DataTypeNameNode dt = AntlrQualifiedName.toDataTypeNameNode(ct); - return AstFactoryImpl.FACTORY.PayloadElement(dt); - } - else if (type == AntlrNodeType.AMBIGUOUSNAME) - { - // Similarly to NonRoleArg: cannot syntactically distinguish right now between SimplePayloadTypeNode and ParameterNode - AmbigNameNode an = AntlrAmbigName.toAmbigNameNode(ct); - return AstFactoryImpl.FACTORY.PayloadElement(an); - }*/ - if (type == AntlrNodeType.DELEGATION) - { - RoleNode rn = AntlrSimpleName.toRoleNode((CommonTree) ct.getChild(0), af); - //GProtocolNameNode gpnn = AntlrQualifiedName.toGProtocolNameNode((CommonTree) ct.getChild(1)); // FIXME: - GProtocolNameNode gpnn = AntlrQualifiedName.toGProtocolNameNode((CommonTree) ct.getChild(1), af); - return af.GDelegationElem(ct, gpnn, rn); - //throw new RuntimeException("Shouldn't get in here: " + ct); - } - else if (type == AntlrNodeType.QUALIFIEDNAME) - { - if (ct.getChildCount() > 1) - { - DataTypeNode dt = AntlrQualifiedName.toDataTypeNameNode(ct, af); - //return AstFactoryImpl.FACTORY.PayloadElem(dt); - return af.UnaryPayloadElem(ct, dt); // return and dt share same ct in this case - } - else - { - // Similarly to NonRoleArg: cannot syntactically distinguish right now between SimplePayloadTypeNode and ParameterNode - AmbigNameNode an = AntlrAmbigName.toAmbigNameNode(ct, af); - return af.UnaryPayloadElem(ct, an); - } - } - else - { - throw new RuntimeException("Shouldn't get in here: " + ct); - } - } - - public static final List getPayloadElements(CommonTree ct) - { - return (ct.getChildCount() == 0) - ? Collections.emptyList() - : AntlrToScribParserUtil.toCommonTreeList(ct.getChildren()); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrRoleArg.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrRoleArg.java deleted file mode 100644 index b9f6313ae..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrRoleArg.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.RoleArg; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; - -public class AntlrRoleArg -{ - public static final int ARG_CHILD_INDEX = 0; - - public static RoleArg parseRoleArg(AntlrToScribParser parser, CommonTree ct, AstFactory af) - { - RoleNode role = AntlrSimpleName.toRoleNode(getArgChild(ct), af); - return af.RoleArg(ct, role); - } - - public static CommonTree getArgChild(CommonTree ct) - { - return (CommonTree) ct.getChild(ARG_CHILD_INDEX); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrRoleArgList.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrRoleArgList.java deleted file mode 100644 index 126b41e26..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrRoleArgList.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast; - -import java.util.LinkedList; -import java.util.List; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.RoleArg; -import org.scribble.ast.RoleArgList; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.AntlrToScribParserUtil; -import org.scribble.util.ScribParserException; - -public class AntlrRoleArgList -{ - public static RoleArgList parseRoleArgList(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - //List ris = getRoleInstantiationChildren(ct).stream().map((ri) -> (RoleArg) parser.parse(ri)).collect(Collectors.toList()); - List ris = new LinkedList<>(); - for (CommonTree ri : getRoleInstantiationChildren(ct)) - { - ris.add((RoleArg) parser.parse(ri, af)); - } - return af.RoleArgList(ct, ris); - } - - public static final List getRoleInstantiationChildren(CommonTree ct) - { - return AntlrToScribParserUtil.toCommonTreeList(ct.getChildren()); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrRoleDecl.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrRoleDecl.java deleted file mode 100644 index 256dc630c..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrRoleDecl.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.RoleDecl; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; - -public class AntlrRoleDecl -{ - public static final int NAME_CHILD_INDEX = 0; - - //public static RoleNode parseRoleDecl(AntlrModuleParser parser, CommonTree ct) - public static RoleDecl parseRoleDecl(AntlrToScribParser parser, CommonTree ct, AstFactory af) - { - RoleNode name = AntlrSimpleName.toRoleNode(getNameChild(ct), af); - return af.RoleDecl(ct, name); - } - - public static CommonTree getNameChild(CommonTree ct) - { - return (CommonTree) ct.getChild(NAME_CHILD_INDEX); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrRoleDeclList.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrRoleDeclList.java deleted file mode 100644 index 75e4bcd24..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/AntlrRoleDeclList.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast; - -import java.util.LinkedList; -import java.util.List; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.RoleDecl; -import org.scribble.ast.RoleDeclList; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.AntlrToScribParserUtil; -import org.scribble.util.ScribParserException; - -public class AntlrRoleDeclList -{ - public static RoleDeclList parseRoleDeclList(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - //List rds = getRoleDeclChildren(ct).stream().map((pd) -> (RoleDecl) parser.parse(pd)).collect(Collectors.toList()); - List rds = new LinkedList<>(); - for (CommonTree pd : getRoleDeclChildren(ct)) - { - rds.add((RoleDecl) parser.parse(pd, af)); - } - return af.RoleDeclList(ct, rds); - } - - public static List getRoleDeclChildren(CommonTree ct) - { - return AntlrToScribParserUtil.toCommonTreeList(ct.getChildren()); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGChoice.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGChoice.java deleted file mode 100644 index 35ac4a159..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGChoice.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global; - -import java.util.LinkedList; -import java.util.List; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.global.GChoice; -import org.scribble.ast.global.GProtocolBlock; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.AntlrToScribParserUtil; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; -import org.scribble.util.ScribParserException; - -public class AntlrGChoice -{ - public static final int SUBJECT_CHILD_INDEX = 0; - public static final int BLOCK_CHILDREN_START_INDEX = 1; - - public static GChoice parseGChoice(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - RoleNode subj = AntlrSimpleName.toRoleNode(getSubjectChild(ct), af); - /*List blocks = - getBlockChildren(ct).stream().map((b) -> (GProtocolBlock) parser.parse(b)).collect(Collectors.toList());*/ - List blocks = new LinkedList<>(); - for (CommonTree b : getBlockChildren(ct)) - { - blocks.add((GProtocolBlock) parser.parse(b, af)); - } - return af.GChoice(ct, subj, blocks); - } - - public static CommonTree getSubjectChild(CommonTree ct) - { - return (CommonTree) ct.getChild(SUBJECT_CHILD_INDEX); - } - - public static List getBlockChildren(CommonTree ct) - { - List children = ct.getChildren(); - return AntlrToScribParserUtil.toCommonTreeList(children.subList(BLOCK_CHILDREN_START_INDEX, children.size())); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGConnect.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGConnect.java deleted file mode 100644 index 277b33b88..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGConnect.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.MessageNode; -import org.scribble.ast.global.GConnect; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; -import org.scribble.util.ScribParserException; - -// Factor with AntlrGMessageTransfer? -public class AntlrGConnect -{ - public static final int MESSAGE_CHILD_INDEX = 2; // Different order than AntlrGMessageTransfer - public static final int SOURCE_CHILD_INDEX = 0; - public static final int DESTINATION_CHILD_INDEX = 1; - - public static GConnect parseGConnect(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - RoleNode src = AntlrSimpleName.toRoleNode(getSourceChild(ct), af); - MessageNode msg = AntlrGMessageTransfer.parseMessage(parser, getMessageChild(ct), af); - RoleNode dest = AntlrSimpleName.toRoleNode(getDestinationChild(ct), af); - return af.GConnect(ct, src, msg, dest); - //return AstFactoryImpl.FACTORY.GConnect(src, dest); - } - - public static CommonTree getMessageChild(CommonTree ct) - { - return (CommonTree) ct.getChild(MESSAGE_CHILD_INDEX); - } - - public static CommonTree getSourceChild(CommonTree ct) - { - return (CommonTree) ct.getChild(SOURCE_CHILD_INDEX); - } - - public static CommonTree getDestinationChild(CommonTree ct) - { - return (CommonTree) ct.getChild(DESTINATION_CHILD_INDEX); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGContinue.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGContinue.java deleted file mode 100644 index e5f338120..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGContinue.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.global.GContinue; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; - -public class AntlrGContinue -{ - public static final int LABEL_CHILD_INDEX = 0; - - public static GContinue parseGContinue(AntlrToScribParser parser, CommonTree ct, AstFactory af) - { - RecVarNode recvar = AntlrSimpleName.toRecVarNode(getRecVarChild(ct), af); - return af.GContinue(ct, recvar); - } - - public static final CommonTree getRecVarChild(CommonTree ct) - { - return (CommonTree) ct.getChild(LABEL_CHILD_INDEX); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGDisconnect.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGDisconnect.java deleted file mode 100644 index 671312bd2..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGDisconnect.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.global.GDisconnect; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; - -// Factor with AntlrGMessageTransfer/AntlrGConnect -public class AntlrGDisconnect -{ - public static final int SOURCE_CHILD_INDEX = 0; - public static final int DESTINATION_CHILD_INDEX = 1; - - public static GDisconnect parseGDisconnect(AntlrToScribParser parser, CommonTree ct, AstFactory af) - { - RoleNode src = AntlrSimpleName.toRoleNode(getSourceChild(ct), af); - RoleNode dest = AntlrSimpleName.toRoleNode(getDestinationChild(ct), af); - return af.GDisconnect(ct, src, dest); - } - - public static CommonTree getSourceChild(CommonTree ct) - { - return (CommonTree) ct.getChild(SOURCE_CHILD_INDEX); - } - - public static CommonTree getDestinationChild(CommonTree ct) - { - return (CommonTree) ct.getChild(DESTINATION_CHILD_INDEX); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGDo.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGDo.java deleted file mode 100644 index ebc589937..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGDo.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.NonRoleArgList; -import org.scribble.ast.RoleArgList; -import org.scribble.ast.global.GDo; -import org.scribble.ast.name.qualified.GProtocolNameNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.ast.name.AntlrQualifiedName; -import org.scribble.util.ScribParserException; - -public class AntlrGDo -{ - public static final int MEMBERNAME_CHILD_INDEX = 0; - public static final int ARGUMENTLIST_CHILD_INDEX = 1; - public static final int ROLEINSTANTIATIONLIST_CHILD_INDEX = 2; - - public static GDo parseGDo(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - RoleArgList ril = (RoleArgList) parser.parse(getRoleArgListChild(ct), af); - NonRoleArgList al = (NonRoleArgList) parser.parse(getNonRoleArgListChild(ct), af); - GProtocolNameNode pnn = AntlrQualifiedName.toGProtocolNameNode(getProtocolNameChild(ct), af); - return af.GDo(ct, ril, al, pnn); - } - - public static CommonTree getProtocolNameChild(CommonTree ct) - { - return (CommonTree) ct.getChild(MEMBERNAME_CHILD_INDEX); - } - - public static CommonTree getNonRoleArgListChild(CommonTree ct) - { - return (CommonTree) ct.getChild(ARGUMENTLIST_CHILD_INDEX); - } - - public static CommonTree getRoleArgListChild(CommonTree ct) - { - return (CommonTree) ct.getChild(ROLEINSTANTIATIONLIST_CHILD_INDEX); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGInteractionSequence.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGInteractionSequence.java deleted file mode 100644 index d938913ce..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGInteractionSequence.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.global.GInteractionNode; -import org.scribble.ast.global.GInteractionSeq; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.AntlrToScribParserUtil; -import org.scribble.util.ScribParserException; - -public class AntlrGInteractionSequence -{ - public static GInteractionSeq parseGInteractionSequence(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - /*List gis = - getInteractionChildren(ct).stream().map((gi) -> (GInteractionNode) parser.parse(gi)).collect(Collectors.toList());*/ - List gis = new LinkedList<>(); - for (CommonTree gi : getInteractionChildren(ct)) - { - gis.add((GInteractionNode) parser.parse(gi, af)); - } - return af.GInteractionSeq(ct, gis); - } - - public static List getInteractionChildren(CommonTree ct) - { - return (ct.getChildCount() == 0) - ? Collections.emptyList() - : AntlrToScribParserUtil.toCommonTreeList(ct.getChildren()); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGInterrupt.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGInterrupt.java deleted file mode 100644 index 218acf38e..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGInterrupt.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global; - -import java.util.List; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.global.GInterrupt; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.AntlrToScribParserUtil; -import org.scribble.util.ScribParserException; - - -public class AntlrGInterrupt -{ - public static final int SOURCE_CHILD_INDEX = 0; - public static final int MESSAGE_CHILDREN_START_INDEX = 1; - - public static GInterrupt parseGInterrupt(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - /*RoleNode src = AntlrSimpleName.toRoleNode(getSourceChild(ct)); - /*List msgs = - getMessageChildren(ct).stream().map((msg) -> AntlrGMessageTransfer.parseMessage(parser, msg)).collect(Collectors.toList()); - * / - List msgs = new LinkedList<>(); - for (CommonTree msg : getMessageChildren(ct)) - { - msgs.add(AntlrGMessageTransfer.parseMessage(parser, msg)); - } - //return new GInterrupt(src, msgs); // Destination roles set by later pass*/ - return null; - } - - public static CommonTree getSourceChild(CommonTree ct) - { - return (CommonTree) ct.getChild(SOURCE_CHILD_INDEX); - } - - public static List getMessageChildren(CommonTree ct) - { - return AntlrToScribParserUtil.toCommonTreeList(ct.getChildren().subList(MESSAGE_CHILDREN_START_INDEX, ct.getChildCount())); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGInterruptible.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGInterruptible.java deleted file mode 100644 index 149c63085..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGInterruptible.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global; - -import java.util.List; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.global.GInterruptible; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.AntlrToScribParserUtil; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; -import org.scribble.util.ScribParserException; - -public class AntlrGInterruptible -{ - public static final int SCOPE_CHILD_INDEX = 0; - public static final int BLOCK_CHILD_INDEX = 1; - public static final int INTERRUPT_CHILDREN_START_INDEX = 2; - - public static GInterruptible parseGInterruptible(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - /*GProtocolBlock block = (GProtocolBlock) parser.parse(getBlockChild(ct)); - /*List interrs = - getInterruptChildren(ct).stream().map((interr) -> (GInterrupt) parser.parse(interr)).collect(Collectors.toList()); - * / - List interrs = new LinkedList<>(); - for (CommonTree interr : getInterruptChildren(ct)) - { - interrs.add((GInterrupt) parser.parse(interr)); - } - if (isScopeImplicit(ct)) - { - //return new GInterruptible(block, interrs); - return null; - } - ScopeNode scope = AntlrSimpleName.toScopeNode(getScopeChild(ct)); - //return new GInterruptible(scope, block, interrs);*/ - return null; - } - - public static boolean isScopeImplicit(CommonTree ct) - { - return AntlrSimpleName.toScopeNode(ct) == null; - } - - public static CommonTree getScopeChild(CommonTree ct) - { - return (CommonTree) ct.getChild(SCOPE_CHILD_INDEX); - } - - public static CommonTree getBlockChild(CommonTree ct) - { - return (CommonTree) ct.getChild(BLOCK_CHILD_INDEX); - } - - public static List getInterruptChildren(CommonTree ct) - { - List children = ct.getChildren(); - return AntlrToScribParserUtil.toCommonTreeList(children.subList(INTERRUPT_CHILDREN_START_INDEX, children.size())); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGMessageTransfer.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGMessageTransfer.java deleted file mode 100644 index 138ca0ec0..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGMessageTransfer.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global; - -import java.util.List; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.MessageNode; -import org.scribble.ast.MessageSigNode; -import org.scribble.ast.global.GMessageTransfer; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.AntlrToScribParserUtil; -import org.scribble.parser.scribble.ScribbleAntlrConstants.AntlrNodeType; -import org.scribble.parser.scribble.ast.name.AntlrAmbigName; -import org.scribble.parser.scribble.ast.name.AntlrQualifiedName; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; -import org.scribble.util.ScribParserException; - -public class AntlrGMessageTransfer -{ - public static final int MESSAGE_CHILD_INDEX = 0; - public static final int SOURCE_CHILD_INDEX = 1; - public static final int DESTINATION_CHILDREN_START_INDEX = 2; - - public static GMessageTransfer parseGMessageTransfer(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - RoleNode src = AntlrSimpleName.toRoleNode(getSourceChild(ct), af); - MessageNode msg = parseMessage(parser, getMessageChild(ct), af); - List dests = - getDestChildren(ct).stream().map(d -> AntlrSimpleName.toRoleNode(d, af)).collect(Collectors.toList()); - return af.GMessageTransfer(ct, src, msg, dests); - } - - public static MessageNode parseMessage(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - AntlrNodeType type = AntlrToScribParserUtil.getAntlrNodeType(ct); - if (type == AntlrNodeType.MESSAGESIGNATURE) - { - return (MessageSigNode) parser.parse(ct, af); - } - else //if (type.equals(AntlrConstants.AMBIGUOUSNAME_NODE_TYPE)) - { - return (ct.getChildCount() == 1) - ? AntlrAmbigName.toAmbigNameNode(ct, af) // parametername or simple messagesignaturename - : AntlrQualifiedName.toMessageSigNameNode(ct, af); - } - } - - public static CommonTree getMessageChild(CommonTree ct) - { - return (CommonTree) ct.getChild(MESSAGE_CHILD_INDEX); - } - - public static CommonTree getSourceChild(CommonTree ct) - { - return (CommonTree) ct.getChild(SOURCE_CHILD_INDEX); - } - - public static List getDestChildren(CommonTree ct) - { - return AntlrToScribParserUtil.toCommonTreeList(ct.getChildren().subList(DESTINATION_CHILDREN_START_INDEX, ct.getChildCount())); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGParallel.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGParallel.java deleted file mode 100644 index 912d505f8..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGParallel.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global; - -import java.util.LinkedList; -import java.util.List; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.global.GParallel; -import org.scribble.ast.global.GProtocolBlock; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.AntlrToScribParserUtil; -import org.scribble.util.ScribParserException; - -public class AntlrGParallel -{ - public static GParallel parseGParallel(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - /*List blocks = - getBlockChildren(ct).stream().map((b) -> (GProtocolBlock) parser.parse(b)).collect(Collectors.toList());*/ - List blocks = new LinkedList<>(); - for (CommonTree b : getBlockChildren(ct)) - { - blocks.add((GProtocolBlock) parser.parse(b, af)); - } - //return new GParallel(blocks); - return null; - } - - public static final List getBlockChildren(CommonTree ct) - { - return AntlrToScribParserUtil.toCommonTreeList(ct.getChildren()); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGProtocolBlock.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGProtocolBlock.java deleted file mode 100644 index 9159ab738..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGProtocolBlock.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.global.GInteractionSeq; -import org.scribble.ast.global.GProtocolBlock; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.util.ScribParserException; - -public class AntlrGProtocolBlock -{ - public static final int INTERACTIONSEQUENCE_CHILD_INDEX = 0; - - public static GProtocolBlock parseGProtocolBlock(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - GInteractionSeq gis = (GInteractionSeq) parser.parse(getInteractionSequenceChild(ct), af); - return af.GProtocolBlock(ct, gis); - } - - public static final CommonTree getInteractionSequenceChild(CommonTree ct) - { - return (CommonTree) ct.getChild(INTERACTIONSEQUENCE_CHILD_INDEX); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGProtocolDecl.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGProtocolDecl.java deleted file mode 100644 index 263dd03d3..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGProtocolDecl.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global; - -import java.util.LinkedList; -import java.util.List; -import java.util.stream.Collectors; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.global.GProtocolDecl; -import org.scribble.ast.global.GProtocolDef; -import org.scribble.ast.global.GProtocolHeader; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.util.ScribParserException; - -public class AntlrGProtocolDecl -{ - public static final int HEADER_CHILD_INDEX = 0; - public static final int BODY_CHILD_INDEX = 1; - //public static final int EXPLICIT_CONNECTIONS_FLAG_INDEX = 2; - public static final int MODIFIERS_CHILD_INDEX = 2; - - public static GProtocolDecl parseGPrototocolDecl(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - GProtocolHeader header = (GProtocolHeader) parser.parse(getHeaderChild(ct), af); - GProtocolDef def = (GProtocolDef) parser.parse(getBodyChild(ct), af); - List modifiers = new LinkedList<>(); - /*if (isExplicitConnections(ct)) - { - modifiers.add(GProtocolDecl.Modifiers.EXPLICIT); - }*/ - if (hasModifiersChild(ct)) - { - for (CommonTree mod :getModifierChildren(ct)) - { - switch (mod.getText()) - { - case "aux": modifiers.add(GProtocolDecl.Modifiers.AUX); break; - case "explicit": modifiers.add(GProtocolDecl.Modifiers.EXPLICIT); break; - default: throw new RuntimeException("TODO: " + mod); - } - } - } - return af.GProtocolDecl(ct, modifiers, header, def); - } - - public static CommonTree getHeaderChild(CommonTree ct) - { - return (CommonTree) ct.getChild(HEADER_CHILD_INDEX); - } - - public static CommonTree getBodyChild(CommonTree ct) - { - return (CommonTree) ct.getChild(BODY_CHILD_INDEX); - } - - public static boolean hasModifiersChild(CommonTree ct) - { - return ct.getChildCount() > MODIFIERS_CHILD_INDEX; - } - - public static List getModifierChildren(CommonTree ct) - { - //return (CommonTree) ct.getChild(MODIFIERS_CHILD_INDEX); - return ((List) ((CommonTree) ct.getChild(MODIFIERS_CHILD_INDEX)).getChildren()).stream() - .map((c) -> (CommonTree) c).collect(Collectors.toList()); - } - - /*public static boolean isExplicitConnections(CommonTree ct) - { - return ct.getChildCount() > EXPLICIT_CONNECTIONS_FLAG_INDEX; - }*/ -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGProtocolDefinition.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGProtocolDefinition.java deleted file mode 100644 index f8d362f71..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGProtocolDefinition.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.global.GProtocolBlock; -import org.scribble.ast.global.GProtocolDef; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.util.ScribParserException; - -public class AntlrGProtocolDefinition -{ - public static final int BLOCK_CHILD_INDEX = 0; - - public static GProtocolDef parseGProtocolDefinition(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - GProtocolBlock gpb = (GProtocolBlock) parser.parse(getBlockChild(ct), af); - return af.GProtocolDef(ct, gpb); - } - - public static CommonTree getBlockChild(CommonTree ct) - { - return (CommonTree) ct.getChild(BLOCK_CHILD_INDEX); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGProtocolHeader.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGProtocolHeader.java deleted file mode 100644 index 57d31035f..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGProtocolHeader.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.NonRoleParamDeclList; -import org.scribble.ast.RoleDeclList; -import org.scribble.ast.global.GProtocolHeader; -import org.scribble.ast.name.qualified.GProtocolNameNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; -import org.scribble.util.ScribParserException; - -public class AntlrGProtocolHeader -{ - public static final int NAME_CHILD_INDEX = 0; - public static final int PARAMETERDECLLIST_CHILD_INDEX = 1; - public static final int ROLEDECLLIST_CHILD_INDEX = 2; - - public static GProtocolHeader parseGProtocolHeader(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - GProtocolNameNode name = AntlrSimpleName.toGProtocolNameNode(getNameChild(ct), af); - RoleDeclList rdl = (RoleDeclList) parser.parse(getRoleDeclListChild(ct), af); - NonRoleParamDeclList pdl = (NonRoleParamDeclList) parser.parse(getParamDeclListChild(ct), af); - return af.GProtocolHeader(ct, name, rdl, pdl); - } - - public static CommonTree getNameChild(CommonTree ct) - { - return (CommonTree) ct.getChild(NAME_CHILD_INDEX); - } - - public static CommonTree getRoleDeclListChild(CommonTree ct) - { - return (CommonTree) ct.getChild(ROLEDECLLIST_CHILD_INDEX); - } - - public static CommonTree getParamDeclListChild(CommonTree ct) - { - return (CommonTree) ct.getChild(PARAMETERDECLLIST_CHILD_INDEX); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGRecursion.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGRecursion.java deleted file mode 100644 index 1906a7d08..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGRecursion.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.global.GProtocolBlock; -import org.scribble.ast.global.GRecursion; -import org.scribble.ast.name.simple.RecVarNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; -import org.scribble.util.ScribParserException; - -public class AntlrGRecursion -{ - public static final int RECURSIONVAR_CHILD_INDEX = 0; - public static final int BLOCK_CHILD_INDEX = 1; - - public static GRecursion parseGRecursion(AntlrToScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException - { - RecVarNode recvar = AntlrSimpleName.toRecVarNode(getRecVarChild(ct), af); - GProtocolBlock block = (GProtocolBlock) parser.parse(getBlockChild(ct), af); - return af.GRecursion(ct, recvar, block); - } - - public static final CommonTree getRecVarChild(CommonTree ct) - { - return (CommonTree) ct.getChild(RECURSIONVAR_CHILD_INDEX); - } - - public static final CommonTree getBlockChild(CommonTree ct) - { - return (CommonTree) ct.getChild(BLOCK_CHILD_INDEX); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGWrap.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGWrap.java deleted file mode 100644 index 654a05f01..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/global/AntlrGWrap.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.global; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.global.GWrap; -import org.scribble.ast.name.simple.RoleNode; -import org.scribble.parser.scribble.AntlrToScribParser; -import org.scribble.parser.scribble.ast.name.AntlrSimpleName; - -// Factor with AntlrGMessageTransfer? -public class AntlrGWrap -{ - public static final int SOURCE_CHILD_INDEX = 0; - public static final int DESTINATION_CHILD_INDEX = 1; - - public static GWrap parseGWrap(AntlrToScribParser parser, CommonTree ct, AstFactory af) - { - RoleNode src = AntlrSimpleName.toRoleNode(getSourceChild(ct), af); - RoleNode dest = AntlrSimpleName.toRoleNode(getDestinationChild(ct), af); - return af.GWrap(ct, src, dest); - } - - public static CommonTree getSourceChild(CommonTree ct) - { - return (CommonTree) ct.getChild(SOURCE_CHILD_INDEX); - } - - public static CommonTree getDestinationChild(CommonTree ct) - { - return (CommonTree) ct.getChild(DESTINATION_CHILD_INDEX); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/name/AntlrAmbigName.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/name/AntlrAmbigName.java deleted file mode 100644 index 7baca3102..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/name/AntlrAmbigName.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.name; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.name.simple.AmbigNameNode; - -// FIXME: refactor into AntlrSimple/QualifiedName? -- need to separate ambig simple and qualified? -public class AntlrAmbigName -{ - public static AmbigNameNode toAmbigNameNode(CommonTree ct, AstFactory af) - { - return af.AmbiguousNameNode(getNameChild(ct), getName(ct)); - } - - private static CommonTree getNameChild(CommonTree ct) - { - return (CommonTree) ct.getChild(0); - } - - private static String getName(CommonTree ct) - { - return AntlrSimpleName.getName(getNameChild(ct)); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/name/AntlrQualifiedName.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/name/AntlrQualifiedName.java deleted file mode 100644 index 2ebb64b6c..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/name/AntlrQualifiedName.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.name; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.name.qualified.DataTypeNode; -import org.scribble.ast.name.qualified.GProtocolNameNode; -import org.scribble.ast.name.qualified.LProtocolNameNode; -import org.scribble.ast.name.qualified.MessageSigNameNode; -import org.scribble.ast.name.qualified.ModuleNameNode; -import org.scribble.type.kind.DataTypeKind; -import org.scribble.type.kind.Global; -import org.scribble.type.kind.Local; -import org.scribble.type.kind.ModuleKind; -import org.scribble.type.kind.SigKind; - -public class AntlrQualifiedName -{ - protected static String[] getElements(CommonTree ct) - { - int count = ct.getChildCount(); - String[] names = new String[count]; - for (int i = 0; i < count; i++) - { - names[i] = AntlrSimpleName.getName((CommonTree) ct.getChild(i)); - } - return names; - } - - public static ModuleNameNode toModuleNameNode(CommonTree ct, AstFactory af) - { - return (ModuleNameNode) af.QualifiedNameNode(ct, ModuleKind.KIND, getElements(ct)); - } - - public static DataTypeNode toDataTypeNameNode(CommonTree ct, AstFactory af) - { - return (DataTypeNode) af.QualifiedNameNode(ct, DataTypeKind.KIND, getElements(ct)); - } - - public static MessageSigNameNode toMessageSigNameNode(CommonTree ct, AstFactory af) - { - return (MessageSigNameNode) af.QualifiedNameNode(ct, SigKind.KIND, getElements(ct)); - } - - public static GProtocolNameNode toGProtocolNameNode(CommonTree ct, AstFactory af) - { - return (GProtocolNameNode) af.QualifiedNameNode(ct, Global.KIND, getElements(ct)); - } - - public static LProtocolNameNode toLProtocolNameNode(CommonTree ct, AstFactory af) - { - return (LProtocolNameNode) af.QualifiedNameNode(ct, Local.KIND, getElements(ct)); - } -} diff --git a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/name/AntlrSimpleName.java b/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/name/AntlrSimpleName.java deleted file mode 100644 index 0c66f75fa..000000000 --- a/scribble-parser/src/main/java/org/scribble/parser/scribble/ast/name/AntlrSimpleName.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribble.ast.name; - -import org.antlr.runtime.tree.CommonTree; -import org.scribble.ast.AstFactory; -import org.scribble.ast.name.qualified.DataTypeNode; -import org.scribble.ast.name.qualified.GProtocolNameNode; -import org.scribble.ast.name.qualified.LProtocolNameNode; -import org.scribble.ast.name.qualified.MessageSigNameNode; -import org.scribble.ast.name.qualified.ModuleNameNode; -import org.scribble.ast.name.simple.NonRoleParamNode; -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.ScopeNode; -import org.scribble.parser.scribble.ScribbleAntlrConstants; -import org.scribble.type.kind.DataTypeKind; -import org.scribble.type.kind.Global; -import org.scribble.type.kind.Local; -import org.scribble.type.kind.ModuleKind; -import org.scribble.type.kind.NonRoleParamKind; -import org.scribble.type.kind.OpKind; -import org.scribble.type.kind.RecVarKind; -import org.scribble.type.kind.RoleKind; -import org.scribble.type.kind.SigKind; - -public class AntlrSimpleName -{ - public static ModuleNameNode toModuleNameNode(CommonTree ct, AstFactory af) - { - return (ModuleNameNode) af.QualifiedNameNode(ct, ModuleKind.KIND, getName(ct)); // Cannot use SimpleNameNode because qualified uses the node's elements, not the node's text itself - } - - public static GProtocolNameNode toGProtocolNameNode(CommonTree ct, AstFactory af) - { - return (GProtocolNameNode) af.QualifiedNameNode(ct, Global.KIND, getName(ct)); // Cannot use SimpleNameNode because qualified uses the node's elements, not the node's text itself - } - - public static LProtocolNameNode toLProtocolNameNode(CommonTree ct, AstFactory af) - { - return (LProtocolNameNode) af.QualifiedNameNode(ct, Local.KIND, getName(ct)); - } - - public static DataTypeNode toDataTypeNameNode(CommonTree ct, AstFactory af) - { - return (DataTypeNode) af.QualifiedNameNode(ct, DataTypeKind.KIND, getName(ct)); - } - - public static MessageSigNameNode toMessageSigNameNode(CommonTree ct, AstFactory af) - { - return (MessageSigNameNode) af.QualifiedNameNode(ct, SigKind.KIND, getName(ct)); - } - - public static RoleNode toRoleNode(CommonTree ct, AstFactory af) - { - return (RoleNode) af.SimpleNameNode(ct, RoleKind.KIND, getName(ct)); - } - - public static NonRoleParamNode toParamNode(K kind, CommonTree ct, AstFactory af) - { - return af.NonRoleParamNode(ct, kind, getName(ct)); - } - - public static OpNode toOpNode(CommonTree ct, AstFactory af) - { - String op = getName(ct); - return op.equals(ScribbleAntlrConstants.ANTLR_EMPTY_OPERATOR) - ? (OpNode) af.SimpleNameNode(ct, OpKind.KIND, OpNode.EMPTY_OPERATOR_IDENTIFIER) - : (OpNode) af.SimpleNameNode(ct, OpKind.KIND, getName(ct)); - } - - public static ScopeNode toScopeNode(CommonTree ct) - { - /*String scope = getName(ct); - if (scope.equals(ANTLR_NO_SCOPE)) - { - return null; - }*/ - throw new RuntimeException("TODO: " + ct); - } - - public static RecVarNode toRecVarNode(CommonTree ct, AstFactory af) - { - return (RecVarNode) af.SimpleNameNode(ct, RecVarKind.KIND, getName(ct)); - } - - public static String getName(CommonTree ct) - { - return ct.getText(); - } -} diff --git a/scribble-parser/src/test/resources/scribble/examples/GDo.scr b/scribble-parser/src/test/resources/scribble/examples/GDo.scr index 64e2e7ee3..8b8e171ec 100644 --- a/scribble-parser/src/test/resources/scribble/examples/GDo.scr +++ b/scribble-parser/src/test/resources/scribble/examples/GDo.scr @@ -3,11 +3,18 @@ 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 as OtherBuyer,Seller as OtherSeller); - do myscope: OtherProtocol(Buyer as OtherBuyer,Seller as OtherSeller); - do a.b.c.OtherProtocol(Buyer as OtherBuyer,Seller as OtherSeller); - do OtherProtocol(Buyer as OtherBuyer,Seller as OtherSeller); - do a.b.c.OtherProtocol(Buyer as OtherBuyer,Seller as OtherSeller); - do myscope: a.b.c.OtherProtocol(Buyer as OtherBuyer,Seller as OtherSeller); +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/GInterruptible.scr b/scribble-parser/src/test/resources/scribble/examples/GInterruptible.scr deleted file mode 100644 index b55e4eca1..000000000 --- a/scribble-parser/src/test/resources/scribble/examples/GInterruptible.scr +++ /dev/null @@ -1,10 +0,0 @@ -module scribble.examples.GInterruptible; - -global protocol GInterruptibleTest(role Buyer,role Seller) { - interruptible MyLabel: { - buy(Order) from Buyer to Seller; - } with { - sell(Order),MesgParam by Seller; - cancel(Order) by Seller; - } -} diff --git a/scribble-parser/src/test/resources/scribble/examples/GMessage.scr b/scribble-parser/src/test/resources/scribble/examples/GMessage.scr index 7b0507312..ad361a2ba 100644 --- a/scribble-parser/src/test/resources/scribble/examples/GMessage.scr +++ b/scribble-parser/src/test/resources/scribble/examples/GMessage.scr @@ -3,16 +3,18 @@ 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(o:Order,c:Customer) from Buyer to SellerA; - buy(Order) from Buyer to SellerA,SellerB; - buy(ord:Order) from Buyer to SellerA; +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; } -global protocol PlaceOrder(role Buyer,role Seller) { +aux global protocol PlaceOrder(role Buyer, role Seller) { + } -global protocol Receipt(role Buyer,role Seller) { -} \ No newline at end of file +aux global protocol Receipt(role Buyer, role Seller) { + +} diff --git a/scribble-parser/src/test/resources/scribble/examples/GParallel.scr b/scribble-parser/src/test/resources/scribble/examples/GParallel.scr deleted file mode 100644 index 2ffee9e3f..000000000 --- a/scribble-parser/src/test/resources/scribble/examples/GParallel.scr +++ /dev/null @@ -1,12 +0,0 @@ -module scribble.examples.GParallel; - -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 GParallelTest(role Buyer,role Seller) { - par { - buy(Order) from Buyer to Seller; - } and { - buy(QuoteRequest) from Buyer to Seller; - } -} diff --git a/scribble-parser/src/test/resources/scribble/examples/GProtocol.scr b/scribble-parser/src/test/resources/scribble/examples/GProtocol.scr index 07c1d04a0..8065d0916 100644 --- a/scribble-parser/src/test/resources/scribble/examples/GProtocol.scr +++ b/scribble-parser/src/test/resources/scribble/examples/GProtocol.scr @@ -1,14 +1,16 @@ module scribble.examples.GProtocol; -global protocol GMessageTest(role Buyer,role SellerA,role SellerB) { +global protocol GMessageTest(role Buyer, role SellerA, role SellerB) { + } -global protocol Order(role Buyer,role Seller) { +global protocol Order(role Buyer, role Seller) { + } -global protocol Receipt(role Buyer as B,role Seller as S) { +global protocol Receipt(role Buyer, role Seller) { + } -global protocol GMessageTest2(role Buyer,role SellerA,role SellerB) instantiates GMessageTest(Buyer,SellerA,SellerB); +//global protocol GMessageTest2(role Buyer,role SellerA,role SellerB) instantiates GMessageTest(Buyer,SellerA,SellerB); -global protocol Order2(role Buyer,role Seller) instantiates Order(Buyer,Seller); diff --git a/scribble-parser/src/test/resources/scribble/examples/GRecursion.scr b/scribble-parser/src/test/resources/scribble/examples/GRecursion.scr index b8f1da021..a4bef2011 100644 --- a/scribble-parser/src/test/resources/scribble/examples/GRecursion.scr +++ b/scribble-parser/src/test/resources/scribble/examples/GRecursion.scr @@ -2,7 +2,7 @@ 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) { +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 index 12d3e843e..2e7f71069 100644 --- a/scribble-parser/src/test/resources/scribble/examples/Imports.scr +++ b/scribble-parser/src/test/resources/scribble/examples/Imports.scr @@ -1,8 +1,9 @@ module scribble.examples.Imports; import scribble.examples.GMessage; -from scribble.examples.GMessage import PlaceOrder; -from scribble.examples.GMessage import Receipt as OrderReceipt; +//from scribble.examples.GMessage import PlaceOrder; +//from scribble.examples.GMessage import Receipt as OrderReceipt; + +global protocol ImportsTest(role Buyer, role Seller) { -global protocol ImportsTest(role Buyer,role Seller as MySeller) { } diff --git a/scribble-parser/src/test/resources/scribble/examples/LChoice.scr b/scribble-parser/src/test/resources/scribble/examples/LChoice.scr index f7904b561..8cce478d9 100644 --- a/scribble-parser/src/test/resources/scribble/examples/LChoice.scr +++ b/scribble-parser/src/test/resources/scribble/examples/LChoice.scr @@ -3,8 +3,8 @@ 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 at Buyer(role Buyer,role Seller) { - choice at Buyer { +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 index f8ab8e0da..e34624fa6 100644 --- a/scribble-parser/src/test/resources/scribble/examples/LDo.scr +++ b/scribble-parser/src/test/resources/scribble/examples/LDo.scr @@ -1,10 +1,8 @@ module scribble.examples.LDo; -local protocol LDoTest at Buyer(role Seller) { - do OtherProtocol(Buyer as OtherBuyer,Seller as OtherSeller); - do myscope: OtherProtocol(Buyer as OtherBuyer,Seller as OtherSeller); - do a.b.c.OtherProtocol(Buyer as OtherBuyer,Seller as OtherSeller); - do OtherProtocol(Buyer as OtherBuyer,Seller as OtherSeller); - do a.b.c.OtherProtocol(Buyer as OtherBuyer,Seller as OtherSeller); - do myscope: a.b.c.OtherProtocol(Buyer as OtherBuyer,Seller as OtherSeller); +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/LInterruptible.scr b/scribble-parser/src/test/resources/scribble/examples/LInterruptible.scr deleted file mode 100644 index 6b8f0e910..000000000 --- a/scribble-parser/src/test/resources/scribble/examples/LInterruptible.scr +++ /dev/null @@ -1,12 +0,0 @@ -module scribble.examples.LInterruptible; - -type "{http://www.acme.com/financial}Order" from "http://www.acme.com/schemas/Order.xsd" as Order; - -local protocol LInterruptibleTest at Buyer(role Buyer,role Seller) { - interruptible MyLabel: { - buy(Order) from Buyer; - } with { - throws sell(Order) to Seller; - catches cancel(Order) from Seller; - } -} diff --git a/scribble-parser/src/test/resources/scribble/examples/LParallel.scr b/scribble-parser/src/test/resources/scribble/examples/LParallel.scr deleted file mode 100644 index b9fecb681..000000000 --- a/scribble-parser/src/test/resources/scribble/examples/LParallel.scr +++ /dev/null @@ -1,12 +0,0 @@ -module scribble.examples.LParallel; - -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 LParallelTest at Buyer(role Buyer,role Seller) { - par { - buy(Order) to Seller; - } and { - buy(QuoteRequest) to Seller; - } -} diff --git a/scribble-parser/src/test/resources/scribble/examples/LProtocol.scr b/scribble-parser/src/test/resources/scribble/examples/LProtocol.scr index 45bd80e89..6bf92ed38 100644 --- a/scribble-parser/src/test/resources/scribble/examples/LProtocol.scr +++ b/scribble-parser/src/test/resources/scribble/examples/LProtocol.scr @@ -1,14 +1,13 @@ module scribble.examples.LProtocol; -local protocol GMessageTest at SellerB(role Buyer,role SellerA,role SellerB) { +local protocol GMessageTest(role Buyer, role SellerA, role SellerB) { } -local protocol Order at Seller(role Buyer,role Seller) { +local protocol Order(role Buyer, self Seller) { } -local protocol Receipt at Seller(role Buyer as B,role Seller as S) { +local protocol Receipt(self Buyer, role Seller) { } -local protocol GMessageTest2 at SellerB(role Buyer,role SellerA,role SellerB) instantiates GMessageTest(Buyer,SellerA,SellerB); +//local protocol GMessageTest2 at SellerB(role Buyer,role SellerA,role SellerB) instantiates GMessageTest(Buyer,SellerA,SellerB); -local protocol Order2 at Seller2(role Buyer2,role Seller2) instantiates Order(Buyer2 as Buyer,Seller2 as Seller); diff --git a/scribble-parser/src/test/resources/scribble/examples/LReceive_Seller.scr b/scribble-parser/src/test/resources/scribble/examples/LReceive_Seller.scr index 80c4e00c7..5c5533db6 100644 --- a/scribble-parser/src/test/resources/scribble/examples/LReceive_Seller.scr +++ b/scribble-parser/src/test/resources/scribble/examples/LReceive_Seller.scr @@ -3,9 +3,7 @@ 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 at Seller(role Buyer,role Seller) { - buy(Order,Customer) from Buyer; - buy(o:Order,c:Customer) from Buyer; +local protocol LReceiveTest(role Buyer, self Seller) { + buy(Order, Customer) from Buyer; buy(Order) from Buyer; - buy(ord: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 index 423e3da10..dc15df9fa 100644 --- a/scribble-parser/src/test/resources/scribble/examples/LRecursion.scr +++ b/scribble-parser/src/test/resources/scribble/examples/LRecursion.scr @@ -2,7 +2,7 @@ module scribble.examples.LRecursion; type "{http://www.acme.com/financial}Order" from "http://www.acme.com/schemas/Order.xsd" as Order; -local protocol LRecursionTest at Buyer(role Buyer,role Seller) { +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 index fc507b84e..72fa7539d 100644 --- a/scribble-parser/src/test/resources/scribble/examples/LSend_Buyer.scr +++ b/scribble-parser/src/test/resources/scribble/examples/LSend_Buyer.scr @@ -3,9 +3,7 @@ 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 at Buyer(role Buyer,role Seller) { - buy(Order,Customer) to Seller; - buy(o:Order,c:Customer) to Seller; +local protocol LSendTest(self Buyer, role Seller) { + buy(Order, Customer) to Seller; buy(Order) to Seller; - buy(ord: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 index 2724a82f1..84284f42e 100644 --- a/scribble-parser/src/test/resources/scribble/examples/Types.scr +++ b/scribble-parser/src/test/resources/scribble/examples/Types.scr @@ -2,5 +2,6 @@ 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 as MySeller) { +global protocol TestTypes(role Buyer, role Seller) { + } diff --git a/scribble-runtime/pom.xml b/scribble-runtime/pom.xml index d94a6b467..c30f9cec7 100644 --- a/scribble-runtime/pom.xml +++ b/scribble-runtime/pom.xml @@ -1,19 +1,10 @@ - + 4.0.0 - - org.scribble - parent - 0.4.4-SNAPSHOT - + + scribble-runtime - scribble-runtime - http://maven.apache.org - - UTF-8 - @@ -22,4 +13,14 @@ + + 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/main/ScribbleRuntimeException.java b/scribble-runtime/src/main/java/org/scribble/main/ScribbleRuntimeException.java deleted file mode 100644 index 505b53659..000000000 --- a/scribble-runtime/src/main/java/org/scribble/main/ScribbleRuntimeException.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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 runtime ScribbleException -public class ScribbleRuntimeException extends Exception -{ - private static final long serialVersionUID = 1L; - - public ScribbleRuntimeException(String s) - { - super(s); - } - - public ScribbleRuntimeException(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/net/ScribInterrupt.java b/scribble-runtime/src/main/java/org/scribble/runtime/message/ScribInterrupt.java similarity index 93% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/ScribInterrupt.java rename to scribble-runtime/src/main/java/org/scribble/runtime/message/ScribInterrupt.java index e66694a34..eb0f4968d 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/ScribInterrupt.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/message/ScribInterrupt.java @@ -11,9 +11,9 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net; +package org.scribble.runtime.message; -import org.scribble.type.name.Op; +import org.scribble.core.type.name.Op; public class ScribInterrupt extends ScribMessage { diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/ScribMessage.java b/scribble-runtime/src/main/java/org/scribble/runtime/message/ScribMessage.java similarity index 95% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/ScribMessage.java rename to scribble-runtime/src/main/java/org/scribble/runtime/message/ScribMessage.java index 70a105011..11a07ad0d 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/ScribMessage.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/message/ScribMessage.java @@ -11,13 +11,13 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net; +package org.scribble.runtime.message; import java.io.Serializable; import java.util.Arrays; import java.util.stream.Collectors; -import org.scribble.type.name.Op; +import org.scribble.core.type.name.Op; public class ScribMessage implements Serializable { @@ -60,7 +60,7 @@ public int hashCode() { int hash = 73; //hash = 31 * hash + super.hashCode(); - hash = 31 * hash + op.hashCode(); + hash = 31 * hash + this.op.hashCode(); hash = 31 * hash + this.payload.hashCode(); return hash; } diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/ScribMessageFormatter.java b/scribble-runtime/src/main/java/org/scribble/runtime/message/ScribMessageFormatter.java similarity index 97% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/ScribMessageFormatter.java rename to scribble-runtime/src/main/java/org/scribble/runtime/message/ScribMessageFormatter.java index 20be87e7e..b46249ace 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/ScribMessageFormatter.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/message/ScribMessageFormatter.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net; +package org.scribble.runtime.message; import java.io.DataInputStream; import java.io.DataOutputStream; diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/BinaryChannelEndpoint.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/BinaryChannelEndpoint.java similarity index 93% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/session/BinaryChannelEndpoint.java rename to scribble-runtime/src/main/java/org/scribble/runtime/net/BinaryChannelEndpoint.java index d901c7d7f..ae30dbba2 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/BinaryChannelEndpoint.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/BinaryChannelEndpoint.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.session; +package org.scribble.runtime.net; import java.io.IOException; import java.nio.ByteBuffer; @@ -21,9 +21,10 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.runtime.net.ScribInterrupt; -import org.scribble.runtime.net.ScribMessage; +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 { @@ -109,13 +110,13 @@ public synchronized CompletableFuture getFuture() ScribMessage m = read(ticket); if (m instanceof ScribInterrupt) // FIXME: hacked in { - throw new RuntimeScribbleException((Throwable) ((ScribInterrupt) m).payload[0]); + throw new RuntimeScribException((Throwable) ((ScribInterrupt) m).payload[0]); } return m; } catch(IOException e) { - throw new RuntimeScribbleException(e); + throw new RuntimeScribException(e); } finally { @@ -129,7 +130,7 @@ public synchronized CompletableFuture getFuture() return fut; } - protected void sync() throws IOException // Hacky + public void sync() throws IOException // Hacky { try { diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/BinaryChannelWrapper.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/BinaryChannelWrapper.java similarity index 96% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/session/BinaryChannelWrapper.java rename to scribble-runtime/src/main/java/org/scribble/runtime/net/BinaryChannelWrapper.java index 437dc61f7..ee63ed663 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/BinaryChannelWrapper.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/BinaryChannelWrapper.java @@ -11,13 +11,15 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.session; +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) diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/ObjectStreamFormatter.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/ObjectStreamFormatter.java deleted file mode 100644 index 7ccd6d80d..000000000 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/ObjectStreamFormatter.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.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.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 - bb.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; - } - bb.position(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/net/scribsock/SSLSocketChannelServer.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/SSLSocketChannelServer.java similarity index 89% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/SSLSocketChannelServer.java rename to scribble-runtime/src/main/java/org/scribble/runtime/net/SSLSocketChannelServer.java index 854f91e78..bb9d40870 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/SSLSocketChannelServer.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/SSLSocketChannelServer.java @@ -11,13 +11,12 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.scribsock; +package org.scribble.runtime.net; import java.io.IOException; import java.nio.channels.ServerSocketChannel; -import org.scribble.runtime.net.session.SessionEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +import org.scribble.runtime.session.SessionEndpoint; // FIXME: public class SSLSocketChannelServer extends ScribServerSocket diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/SSLSocketChannelWrapper.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/SSLSocketChannelWrapper.java similarity index 99% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/session/SSLSocketChannelWrapper.java rename to scribble-runtime/src/main/java/org/scribble/runtime/net/SSLSocketChannelWrapper.java index a1534a5e9..78847bc7d 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/SSLSocketChannelWrapper.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/SSLSocketChannelWrapper.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.session; +package org.scribble.runtime.net; import java.io.IOException; import java.net.InetSocketAddress; diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/ScribServerSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/ScribServerSocket.java similarity index 77% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/ScribServerSocket.java rename to scribble-runtime/src/main/java/org/scribble/runtime/net/ScribServerSocket.java index 89cdb08c5..1cf3879f5 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/ScribServerSocket.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/ScribServerSocket.java @@ -11,13 +11,12 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.scribsock; +package org.scribble.runtime.net; import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.session.BinaryChannelEndpoint; -import org.scribble.runtime.net.session.SessionEndpoint; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.session.SessionEndpoint; public abstract class ScribServerSocket implements AutoCloseable { @@ -33,11 +32,11 @@ public ScribServerSocket(int port) throws IOException //public abstract BinaryChannelEndpoint accept(MPSTEndpoint se) throws IOException; // synchronize public abstract BinaryChannelEndpoint accept(SessionEndpoint se) throws IOException; // synchronize - public synchronized void bind() throws ScribbleRuntimeException + public synchronized void bind() throws ScribRuntimeException { if (this.reg) { - throw new ScribbleRuntimeException("Server socket already registered."); + throw new ScribRuntimeException("Server socket already registered."); } this.reg = true; } diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/SocketChannelEndpoint.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketChannelEndpoint.java similarity index 96% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/session/SocketChannelEndpoint.java rename to scribble-runtime/src/main/java/org/scribble/runtime/net/SocketChannelEndpoint.java index a005b0b27..6b8eac311 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/SocketChannelEndpoint.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketChannelEndpoint.java @@ -11,13 +11,15 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.session; +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; diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/SocketChannelServer.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketChannelServer.java similarity index 89% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/SocketChannelServer.java rename to scribble-runtime/src/main/java/org/scribble/runtime/net/SocketChannelServer.java index eaecc6942..d301be0ce 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/SocketChannelServer.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketChannelServer.java @@ -11,14 +11,13 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.scribsock; +package org.scribble.runtime.net; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.ServerSocketChannel; -import org.scribble.runtime.net.session.SessionEndpoint; -import org.scribble.runtime.net.session.SocketChannelEndpoint; +import org.scribble.runtime.session.SessionEndpoint; public class SocketChannelServer extends ScribServerSocket { diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/SocketEndpoint.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketEndpoint.java similarity index 94% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/session/SocketEndpoint.java rename to scribble-runtime/src/main/java/org/scribble/runtime/net/SocketEndpoint.java index 132e1e7c8..34f210b9c 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/SocketEndpoint.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketEndpoint.java @@ -11,13 +11,14 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.session; +package org.scribble.runtime.net; import java.io.DataInputStream; import java.io.IOException; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.type.name.Role; +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 diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/SocketWrapper.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketWrapper.java similarity index 97% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/session/SocketWrapper.java rename to scribble-runtime/src/main/java/org/scribble/runtime/net/SocketWrapper.java index b1fc29585..e53b92176 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/SocketWrapper.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketWrapper.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.session; +package org.scribble.runtime.net; import java.io.DataInputStream; import java.io.DataOutputStream; diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/InitSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/InitSocket.java deleted file mode 100644 index 6a0d152f5..000000000 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/InitSocket.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribsock; - -import java.io.IOException; -import java.net.UnknownHostException; -import java.util.concurrent.Callable; - -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.session.BinaryChannelEndpoint; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.Session; -import org.scribble.type.name.Role; - -// 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 ScribbleRuntimeException, UnknownHostException, IOException - { - // Can connect unlimited, as long as not already used via init - if (isUsed()) - { - throw new ScribbleRuntimeException("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, ScribbleRuntimeException - { - //accept(null, role); - if (isUsed()) - { - throw new ScribbleRuntimeException("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, ScribbleRuntimeException - { - if (isUsed()) - { - throw new ScribbleRuntimeException("Socket already initialised: " + this.getClass()); - } - this.se.register(role, this.se.getSelfServerSocket().accept(this.se)); - } - - @Override - public void close() throws ScribbleRuntimeException - { - try - { - this.se.close(); - } - finally - { - if (!this.se.isCompleted()) // Subsumes use -- must be used for sess to be completed - { - throw new ScribbleRuntimeException("Session not completed: " + this.se.self); - } - } - } -} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/OutputSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/OutputSocket.java deleted file mode 100644 index 9da68e16b..000000000 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/OutputSocket.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.scribsock; - -import java.io.IOException; -import java.net.UnknownHostException; -import java.util.concurrent.Callable; - -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.runtime.net.session.BinaryChannelEndpoint; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.Session; -import org.scribble.runtime.net.session.SessionEndpoint; -import org.scribble.type.name.Op; -import org.scribble.type.name.Role; - -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, ScribbleRuntimeException - { - writeScribMessage(peer, new ScribMessage(op, payload)); - } - - protected void writeScribMessage(Role peer, ScribMessage msg) throws IOException, ScribbleRuntimeException - { - 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 ScribbleRuntimeException, UnknownHostException, IOException - { - use(); - //this.se.connect(role, cons, host, port); - MPSTEndpoint.connect(this.se, role, cons, host, port); - } - - // FIXME: check if MPST/ExplicitEndpoint - protected void disconnect(Role role) throws ScribbleRuntimeException, 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/net/session/ExplicitEndpoint.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/session/ExplicitEndpoint.java deleted file mode 100644 index da68e9f1a..000000000 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/ExplicitEndpoint.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.session; - -import java.io.IOException; - -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.ScribMessageFormatter; -import org.scribble.type.name.Role; - -public class ExplicitEndpoint extends SessionEndpoint -{ - public ExplicitEndpoint(S sess, R self, ScribMessageFormatter smf) throws IOException, ScribbleRuntimeException - { - super(sess, self, smf); - } - - // FIXME HACK: "init" really only for MPSTEndpoint? Then refactor into there only - @Override - public void init() throws ScribbleRuntimeException - { - if (this.init) - { - throw new ScribbleRuntimeException("Session endpoint already initialised."); - } - } -} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/MPSTEndpoint.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/session/MPSTEndpoint.java deleted file mode 100644 index f323cf060..000000000 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/MPSTEndpoint.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Copyright 2008 The Scribble Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.session; - -import java.io.IOException; -import java.net.UnknownHostException; -import java.util.concurrent.Callable; - -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.ScribMessageFormatter; -import org.scribble.runtime.net.scribsock.ScribServerSocket; -import org.scribble.type.name.Role; - -// 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, ScribbleRuntimeException - { - super(sess, self, smf); - } - - public void connect(Role role, Callable cons, String host, int port) throws ScribbleRuntimeException, UnknownHostException, IOException - { - MPSTEndpoint.connect(this, role, cons, host, port); - } - - // HACK FIXME: refactor (location, protected, etc) - public static void connect(SessionEndpoint se, 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) - if (se.init) - { - //throw new ScribbleRuntimeException("Socket already initialised: " + this.getClass()); - throw new ScribbleRuntimeException("Socket already initialised: " + se.getClass()); - } - //if (this.chans.containsKey(role)) - if (se.chans.containsKey(role)) - { - throw new ScribbleRuntimeException("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, ScribbleRuntimeException - { - 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, ScribbleRuntimeException - { - //if (this.init) - if (se.init) - { - //throw new ScribbleRuntimeException("Socket already initialised: " + this.getClass()); - throw new ScribbleRuntimeException("Socket already initialised: " + se.getClass()); - } - //if (this.chans.containsKey(role)) - if (se.chans.containsKey(role)) - { - throw new ScribbleRuntimeException("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, ScribbleRuntimeException - { - MPSTEndpoint.disconnect(this, role); - } - - public static void disconnect(SessionEndpoint se, Role role) throws IOException, ScribbleRuntimeException - { - //if (!this.chans.containsKey(role)) - if (!se.chans.containsKey(role)) - { - throw new ScribbleRuntimeException("Not connected to: " + role); - } - //deregister(role); - se.deregister(role); - } -} 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/net/session/EndpointInputQueues.java b/scribble-runtime/src/main/java/org/scribble/runtime/session/EndpointInputQueues.java similarity index 91% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/session/EndpointInputQueues.java rename to scribble-runtime/src/main/java/org/scribble/runtime/session/EndpointInputQueues.java index a3ca8ae34..aef3dcfa0 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/EndpointInputQueues.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/session/EndpointInputQueues.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.session; +package org.scribble.runtime.session; import java.io.IOException; import java.util.HashMap; @@ -20,11 +20,10 @@ import java.util.Map; import java.util.concurrent.CompletableFuture; - -import org.scribble.main.RuntimeScribbleException; -import org.scribble.runtime.net.ScribInterrupt; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.type.name.Role; +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 @@ -90,13 +89,13 @@ public synchronized CompletableFuture getFuture(Role peer) ScribMessage m = dequeue(peer, getTicket(peer)); if (m instanceof ScribInterrupt) // FIXME: hacked in { - throw new RuntimeScribbleException((Throwable) ((ScribInterrupt) m).payload[0]); + throw new RuntimeScribException((Throwable) ((ScribInterrupt) m).payload[0]); } return m; } catch(IOException e) { - throw new RuntimeScribbleException(e); + throw new RuntimeScribException(e); } }); } 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/net/session/OpEnum.java b/scribble-runtime/src/main/java/org/scribble/runtime/session/OpEnum.java similarity index 93% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/session/OpEnum.java rename to scribble-runtime/src/main/java/org/scribble/runtime/session/OpEnum.java index c12567079..64419db70 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/OpEnum.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/session/OpEnum.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.session; +package org.scribble.runtime.session; public interface OpEnum { diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/Principal.java b/scribble-runtime/src/main/java/org/scribble/runtime/session/Principal.java similarity index 95% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/session/Principal.java rename to scribble-runtime/src/main/java/org/scribble/runtime/session/Principal.java index 1f13259c0..0f9d52675 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/Principal.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/session/Principal.java @@ -11,11 +11,11 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.session; +package org.scribble.runtime.session; import java.io.Serializable; -import org.scribble.type.name.Role; +import org.scribble.core.type.name.Role; @Deprecated public class Principal implements Serializable diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/ScribInputSelector.java b/scribble-runtime/src/main/java/org/scribble/runtime/session/ScribInputSelector.java similarity index 96% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/session/ScribInputSelector.java rename to scribble-runtime/src/main/java/org/scribble/runtime/session/ScribInputSelector.java index 76db2d750..5041da9e9 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/ScribInputSelector.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/session/ScribInputSelector.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.session; +package org.scribble.runtime.session; import java.io.IOException; import java.nio.channels.ClosedChannelException; @@ -20,7 +20,8 @@ import java.nio.channels.spi.AbstractSelectableChannel; import java.util.Set; -import org.scribble.type.name.Role; +import org.scribble.core.type.name.Role; +import org.scribble.runtime.net.BinaryChannelEndpoint; public class ScribInputSelector extends Thread { diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/Session.java b/scribble-runtime/src/main/java/org/scribble/runtime/session/Session.java similarity index 83% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/session/Session.java rename to scribble-runtime/src/main/java/org/scribble/runtime/session/Session.java index f4acfd8f8..53f21f628 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/Session.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/session/Session.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.session; +package org.scribble.runtime.session; import java.io.IOException; import java.util.HashMap; @@ -19,10 +19,10 @@ import java.util.Map; import java.util.Random; -import org.scribble.main.ScribbleException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.type.name.GProtocolName; -import org.scribble.type.name.Role; +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 { @@ -32,12 +32,12 @@ public abstract class Session public final List impath; public final String modpath; - public final GProtocolName proto; + 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, GProtocolName proto) + public Session(int id, List impath, String modpath, GProtoName proto) { this.id = id; this.impath = impath; @@ -47,7 +47,7 @@ public Session(int id, List impath, String modpath, GProtocolName proto) Session.sessions.put(id, this); } - public Session(List importPath, String source, GProtocolName proto) + public Session(List importPath, String source, GProtoName proto) { this(getFreshId(), importPath, source, proto); } @@ -73,15 +73,15 @@ public SessionEndpoint project(R role, ScribMessageFormatter }*/ //protected

SessionEndpoint project(R role, ScribMessageFormatter smf) throws ScribbleRuntimeException, IOException //protected void project(MPSTEndpoint se) throws ScribbleRuntimeException, IOException - protected void project(SessionEndpoint se) throws ScribbleRuntimeException, IOException + protected void project(SessionEndpoint se) throws ScribRuntimeException, IOException { if (!getRoles().contains(se.self)) { - throw new ScribbleRuntimeException("Invalid role: " + se.self); + throw new ScribRuntimeException("Invalid role: " + se.self); } if (this.endpoints.containsKey(se.self)) { - throw new ScribbleRuntimeException("Session endpoint already created for: " + 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); @@ -120,11 +120,11 @@ public boolean hasEndpoint(Role role) } //public SessionEndpoint getEndpoint(Role role) throws ScribbleException - public MPSTEndpoint getEndpoint(R role) throws ScribbleException + public MPSTEndpoint getEndpoint(R role) throws ScribException { if (!this.endpoints.containsKey(role)) { - throw new ScribbleException("No endpoint for: " + role); + throw new ScribException("No endpoint for: " + role); } @SuppressWarnings("unchecked") MPSTEndpoint cast = (MPSTEndpoint) this.endpoints.get(role); // FIXME: @@ -136,11 +136,11 @@ public MPSTEndpoint getEndpoint(R role return Session.sessions.containsKey(id); }*/ - public static Session getSession(int id) throws ScribbleException + public static Session getSession(int id) throws ScribException { if (!Session.sessions.containsKey(id)) { - throw new ScribbleException("No such session: " + id); + throw new ScribException("No such session: " + id); } return Session.sessions.get(id); } diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/SessionEndpoint.java b/scribble-runtime/src/main/java/org/scribble/runtime/session/SessionEndpoint.java similarity index 91% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/session/SessionEndpoint.java rename to scribble-runtime/src/main/java/org/scribble/runtime/session/SessionEndpoint.java index df02ea885..c26225fb4 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/session/SessionEndpoint.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/session/SessionEndpoint.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.session; +package org.scribble.runtime.session; import java.io.IOException; import java.nio.channels.SelectionKey; @@ -20,12 +20,14 @@ import java.util.Map; import java.util.Set; -import org.scribble.main.RuntimeScribbleException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -import org.scribble.runtime.net.ScribMessageFormatter; -import org.scribble.runtime.net.scribsock.ScribServerSocket; -import org.scribble.type.name.Role; +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 @@ -49,7 +51,7 @@ public abstract class SessionEndpoint impleme private final ScribInputSelector sel; private final Map keys = new HashMap<>(); - public SessionEndpoint(S sess, R self, ScribMessageFormatter smf) throws IOException, ScribbleRuntimeException + public SessionEndpoint(S sess, R self, ScribMessageFormatter smf) throws IOException, ScribRuntimeException { this.sess = sess; this.self = self; @@ -148,7 +150,7 @@ public BinaryChannelEndpoint getChannelEndpoint(Role role) { if (!this.chans.containsKey(role)) { - throw new RuntimeScribbleException(this.self + " is not connected to: " + role); + throw new RuntimeScribException(this.self + " is not connected to: " + role); } return this.chans.get(role); } @@ -164,7 +166,7 @@ public boolean isCompleted() } @Override - public synchronized void close() throws ScribbleRuntimeException + public synchronized void close() throws ScribRuntimeException { if (!this.closed) { @@ -172,13 +174,13 @@ public synchronized void close() throws ScribbleRuntimeException { this.closed = true; this.sel.close(); - this.servs.values().stream().forEach((ss) -> ss.unbind()); + this.servs.values().forEach(ss -> ss.unbind()); } finally { if (!isCompleted()) // Subsumes use -- must be used for sess to be completed { - throw new ScribbleRuntimeException("Session not completed: " + this.self); + throw new ScribRuntimeException("Session not completed: " + this.self); } } } @@ -189,7 +191,7 @@ public ScribServerSocket getSelfServerSocket() ScribServerSocket ss = this.servs.get(this.self); if (ss == null) { - throw new RuntimeScribbleException("No server registered."); + throw new RuntimeScribException("No server registered."); } return ss; } @@ -260,7 +262,7 @@ public void disconnect(Role role) throws IOException, ScribbleRuntimeException }*/ //public void bind() throws ScribbleRuntimeException - public void init() throws ScribbleRuntimeException + public void init() throws ScribRuntimeException { /*if (this.bound) { @@ -269,7 +271,7 @@ public void init() throws ScribbleRuntimeException //if (!this.initialised) if (this.init) { - throw new ScribbleRuntimeException("Session endpoint already initialised."); + throw new ScribRuntimeException("Session endpoint already initialised."); } //this.bound = true; this.init = true; diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/AcceptSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/AcceptSocket.java similarity index 76% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/AcceptSocket.java rename to scribble-runtime/src/main/java/org/scribble/runtime/statechans/AcceptSocket.java index 64240bc1d..1415ae8e6 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/AcceptSocket.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/AcceptSocket.java @@ -11,15 +11,16 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.scribsock; +package org.scribble.runtime.statechans; import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.Session; -import org.scribble.runtime.net.session.SessionEndpoint; -import org.scribble.type.name.Role; +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 { @@ -35,7 +36,7 @@ protected AcceptSocket(SessionEndpoint ep) this.ep.register(role, ss.accept()); }*/ - protected void accept(ScribServerSocket ss, Role role) throws IOException, ScribbleRuntimeException + protected void accept(ScribServerSocket ss, Role role) throws IOException, ScribRuntimeException { use(); //this.se.accept(ss, role); // FIXME: csat diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/AffineSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/AffineSocket.java similarity index 82% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/AffineSocket.java rename to scribble-runtime/src/main/java/org/scribble/runtime/statechans/AffineSocket.java index 905431653..fd1d1a5c5 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/AffineSocket.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/AffineSocket.java @@ -11,11 +11,11 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.scribsock; +package org.scribble.runtime.statechans; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.Session; -import org.scribble.type.name.Role; +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 diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/BranchSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/BranchSocket.java similarity index 81% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/BranchSocket.java rename to scribble-runtime/src/main/java/org/scribble/runtime/statechans/BranchSocket.java index c15f93d6a..80acc14fa 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/BranchSocket.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/BranchSocket.java @@ -11,11 +11,11 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.scribsock; +package org.scribble.runtime.statechans; -import org.scribble.runtime.net.session.Session; -import org.scribble.runtime.net.session.SessionEndpoint; -import org.scribble.type.name.Role; +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 { diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/CaseSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/CaseSocket.java similarity index 83% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/CaseSocket.java rename to scribble-runtime/src/main/java/org/scribble/runtime/statechans/CaseSocket.java index 86b4a0126..f502d8c03 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/CaseSocket.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/CaseSocket.java @@ -11,11 +11,11 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.scribsock; +package org.scribble.runtime.statechans; -import org.scribble.runtime.net.session.Session; -import org.scribble.runtime.net.session.SessionEndpoint; -import org.scribble.type.name.Role; +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) diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/ConnectSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/ConnectSocket.java similarity index 75% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/ConnectSocket.java rename to scribble-runtime/src/main/java/org/scribble/runtime/statechans/ConnectSocket.java index 79a604520..26a5a8434 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/ConnectSocket.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/ConnectSocket.java @@ -11,17 +11,17 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.scribsock; +package org.scribble.runtime.statechans; import java.io.IOException; import java.net.UnknownHostException; import java.util.concurrent.Callable; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.session.BinaryChannelEndpoint; -import org.scribble.runtime.net.session.MPSTEndpoint; -import org.scribble.runtime.net.session.Session; -import org.scribble.type.name.Role; +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 @@ -38,7 +38,7 @@ protected ConnectSocket(MPSTEndpoint ep) this.ep.register(role, new SocketWrapper(s)); }*/ - protected void connect(Role role, Callable cons, String host, int port) throws ScribbleRuntimeException, UnknownHostException, IOException + 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/net/scribsock/EndSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/EndSocket.java similarity index 82% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/EndSocket.java rename to scribble-runtime/src/main/java/org/scribble/runtime/statechans/EndSocket.java index 81d70d1aa..8ca386cd0 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/EndSocket.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/EndSocket.java @@ -11,12 +11,12 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.scribsock; +package org.scribble.runtime.statechans; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.session.Session; -import org.scribble.runtime.net.session.SessionEndpoint; -import org.scribble.type.name.Role; +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 { @@ -27,7 +27,7 @@ protected EndSocket(SessionEndpoint se) super(se); } - public void end() throws ScribbleRuntimeException + public void end() throws ScribRuntimeException { /*super.use(); this.se.setCompleted();*/ 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/net/scribsock/LinearSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/LinearSocket.java similarity index 81% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/LinearSocket.java rename to scribble-runtime/src/main/java/org/scribble/runtime/statechans/LinearSocket.java index 8f4bb081f..7244c2491 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/LinearSocket.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/LinearSocket.java @@ -11,16 +11,16 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.scribsock; +package org.scribble.runtime.statechans; import java.io.IOException; import java.util.concurrent.Callable; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.session.BinaryChannelWrapper; -import org.scribble.runtime.net.session.Session; -import org.scribble.runtime.net.session.SessionEndpoint; -import org.scribble.type.name.Role; +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 @@ -39,22 +39,22 @@ protected boolean isUsed() } //protected synchronized void use() throws ScribbleRuntimeException - protected void use() throws ScribbleRuntimeException + protected void use() throws ScribRuntimeException { if (this.used) { - throw new ScribbleRuntimeException("Linear socket resource already used: " + this.getClass()); + 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, ScribbleRuntimeException + public void wrapClient(Role peer, Callable cons) throws IOException, ScribRuntimeException { //use(); // FIXME: should be use for proper API operation if (this.used) { - throw new ScribbleRuntimeException("Linear socket resource already used: " + this.getClass()); + throw new ScribRuntimeException("Linear socket resource already used: " + this.getClass()); } try { @@ -72,7 +72,7 @@ public void wrapClient(Role peer, Callable cons) // FIXME: refactor // FIXME: State supertype of T - public static T wrapClient(T s, Role peer, Callable cons) throws IOException, ScribbleRuntimeException + public static T wrapClient(T s, Role peer, Callable cons) throws IOException, ScribRuntimeException { ((LinearSocket) s).wrapClient(peer, cons); return s; 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/net/scribsock/ReceiveSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/ReceiveSocket.java similarity index 82% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/ReceiveSocket.java rename to scribble-runtime/src/main/java/org/scribble/runtime/statechans/ReceiveSocket.java index 40ab017df..f9919c99a 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/ReceiveSocket.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/ReceiveSocket.java @@ -11,17 +11,17 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.scribsock; +package org.scribble.runtime.statechans; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.ScribMessage; -import org.scribble.runtime.net.session.Session; -import org.scribble.runtime.net.session.SessionEndpoint; -import org.scribble.type.name.Role; +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 { @@ -32,7 +32,7 @@ protected ReceiveSocket(SessionEndpoint se) super(se); } - protected ScribMessage readScribMessage(Role peer) throws ClassNotFoundException, IOException, ScribbleRuntimeException + protected ScribMessage readScribMessage(Role peer) throws ClassNotFoundException, IOException, ScribRuntimeException { try { @@ -60,7 +60,7 @@ protected boolean isDone(Role peer) return (this.fut == null) || (this.fut.isDone()); } - protected CompletableFuture getFuture(Role peer) throws ScribbleRuntimeException + protected CompletableFuture getFuture(Role peer) throws ScribRuntimeException { use(); //this.fut = this.ep.getInputQueues().getFuture(peer); diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/ScribSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/ScribSocket.java similarity index 75% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/ScribSocket.java rename to scribble-runtime/src/main/java/org/scribble/runtime/statechans/ScribSocket.java index fcbbcead3..ec296ac75 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/scribsock/ScribSocket.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/ScribSocket.java @@ -11,12 +11,13 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net.scribsock; +package org.scribble.runtime.statechans; -import org.scribble.runtime.net.session.Session; -import org.scribble.runtime.net.session.SessionEndpoint; -import org.scribble.type.name.Role; +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; diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/Buf.java b/scribble-runtime/src/main/java/org/scribble/runtime/util/Buf.java similarity index 95% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/Buf.java rename to scribble-runtime/src/main/java/org/scribble/runtime/util/Buf.java index ca2cc038b..bd04b02ad 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/Buf.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/util/Buf.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net; +package org.scribble.runtime.util; public class Buf { diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/ScribFuture.java b/scribble-runtime/src/main/java/org/scribble/runtime/util/ScribFuture.java similarity index 96% rename from scribble-runtime/src/main/java/org/scribble/runtime/net/ScribFuture.java rename to scribble-runtime/src/main/java/org/scribble/runtime/util/ScribFuture.java index 74f85f8e4..3e2f9a7a2 100644 --- a/scribble-runtime/src/main/java/org/scribble/runtime/net/ScribFuture.java +++ b/scribble-runtime/src/main/java/org/scribble/runtime/util/ScribFuture.java @@ -11,12 +11,14 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.runtime.net; +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

{ diff --git a/scribble-test/pom.xml b/scribble-test/pom.xml index f9a56db5d..49d617a80 100644 --- a/scribble-test/pom.xml +++ b/scribble-test/pom.xml @@ -1,21 +1,10 @@ - + 4.0.0 - - org.scribble - parent - 0.4.4-SNAPSHOT - ../pom.xml - + scribble-test - scribble-test - http://maven.apache.org - - UTF-8 - @@ -26,10 +15,18 @@ org.scribble scribble-parser + org.scribble scribble-cli + + org.scribble + scribble-runtime + junit junit @@ -37,12 +34,19 @@ + + org.scribble + parent + 0.5.1-SNAPSHOT + ../pom.xml + + + - - + + + org.apache.maven.plugins maven-jar-plugin @@ -56,7 +60,31 @@ - + --> + + + + 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/cli/ExecUtil.java b/scribble-test/src/test/java/org/scribble/test/ExecUtil.java similarity index 99% rename from scribble-test/src/test/java/org/scribble/cli/ExecUtil.java rename to scribble-test/src/test/java/org/scribble/test/ExecUtil.java index df3b0ed2c..0d4accb1e 100644 --- a/scribble-test/src/test/java/org/scribble/cli/ExecUtil.java +++ b/scribble-test/src/test/java/org/scribble/test/ExecUtil.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.cli; +package org.scribble.test; import java.io.File; import java.io.IOException; diff --git a/scribble-test/src/test/java/org/scribble/cli/Harness.java b/scribble-test/src/test/java/org/scribble/test/Harness.java similarity index 99% rename from scribble-test/src/test/java/org/scribble/cli/Harness.java rename to scribble-test/src/test/java/org/scribble/test/Harness.java index d8bb9d3ee..e153f17f4 100644 --- a/scribble-test/src/test/java/org/scribble/cli/Harness.java +++ b/scribble-test/src/test/java/org/scribble/test/Harness.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.cli; +package org.scribble.test; import java.io.File; import java.util.Collection; diff --git a/scribble-test/src/test/java/org/scribble/cli/IgnoredDirectoryWhenFilter.java b/scribble-test/src/test/java/org/scribble/test/IgnoredDirectoryWhenFilter.java similarity index 97% rename from scribble-test/src/test/java/org/scribble/cli/IgnoredDirectoryWhenFilter.java rename to scribble-test/src/test/java/org/scribble/test/IgnoredDirectoryWhenFilter.java index 66ed4761e..8e034c56a 100644 --- a/scribble-test/src/test/java/org/scribble/cli/IgnoredDirectoryWhenFilter.java +++ b/scribble-test/src/test/java/org/scribble/test/IgnoredDirectoryWhenFilter.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.cli; +package org.scribble.test; import java.io.File; import java.io.FileFilter; diff --git a/scribble-test/src/test/java/org/scribble/cli/JavaProcessBuilder.java b/scribble-test/src/test/java/org/scribble/test/JavaProcessBuilder.java similarity index 99% rename from scribble-test/src/test/java/org/scribble/cli/JavaProcessBuilder.java rename to scribble-test/src/test/java/org/scribble/test/JavaProcessBuilder.java index 098860927..40f35b6bf 100644 --- a/scribble-test/src/test/java/org/scribble/cli/JavaProcessBuilder.java +++ b/scribble-test/src/test/java/org/scribble/test/JavaProcessBuilder.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.cli; +package org.scribble.test; import java.io.File; import java.util.ArrayList; diff --git a/scribble-test/src/test/java/org/scribble/cli/ScribAllTest.java b/scribble-test/src/test/java/org/scribble/test/ScribAllTest.java similarity index 98% rename from scribble-test/src/test/java/org/scribble/cli/ScribAllTest.java rename to scribble-test/src/test/java/org/scribble/test/ScribAllTest.java index e610e0777..47afda3cf 100644 --- a/scribble-test/src/test/java/org/scribble/cli/ScribAllTest.java +++ b/scribble-test/src/test/java/org/scribble/test/ScribAllTest.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.cli; +package org.scribble.test; import java.util.Collection; import java.util.LinkedList; diff --git a/scribble-test/src/test/java/org/scribble/cli/ScribBadTest.java b/scribble-test/src/test/java/org/scribble/test/ScribBadTest.java similarity index 98% rename from scribble-test/src/test/java/org/scribble/cli/ScribBadTest.java rename to scribble-test/src/test/java/org/scribble/test/ScribBadTest.java index a22b4a1cb..ae15719e1 100644 --- a/scribble-test/src/test/java/org/scribble/cli/ScribBadTest.java +++ b/scribble-test/src/test/java/org/scribble/test/ScribBadTest.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.cli; +package org.scribble.test; import java.util.Collection; diff --git a/scribble-test/src/test/java/org/scribble/cli/ScribGoodTest.java b/scribble-test/src/test/java/org/scribble/test/ScribGoodTest.java similarity index 98% rename from scribble-test/src/test/java/org/scribble/cli/ScribGoodTest.java rename to scribble-test/src/test/java/org/scribble/test/ScribGoodTest.java index 1eeb26133..22203cc43 100644 --- a/scribble-test/src/test/java/org/scribble/cli/ScribGoodTest.java +++ b/scribble-test/src/test/java/org/scribble/test/ScribGoodTest.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.cli; +package org.scribble.test; import java.util.Collection; diff --git a/scribble-test/src/test/java/org/scribble/cli/ScribTestBase.java b/scribble-test/src/test/java/org/scribble/test/ScribTestBase.java similarity index 91% rename from scribble-test/src/test/java/org/scribble/cli/ScribTestBase.java rename to scribble-test/src/test/java/org/scribble/test/ScribTestBase.java index 5d9f3aaca..2780a3fbf 100644 --- a/scribble-test/src/test/java/org/scribble/cli/ScribTestBase.java +++ b/scribble-test/src/test/java/org/scribble/test/ScribTestBase.java @@ -11,7 +11,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ -package org.scribble.cli; +package org.scribble.test; import java.io.File; import java.io.IOException; @@ -19,8 +19,11 @@ import org.junit.Assert; import org.junit.Test; -import org.scribble.main.AntlrSourceException; -import org.scribble.main.ScribbleException; +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: @@ -73,7 +76,7 @@ protected boolean checkSkip() protected void runTest(String dir) throws CommandLineException, AntlrSourceException { - new CommandLine(this.example, CLArgParser.JUNIT_FLAG, CLArgParser.IMPORT_PATH_FLAG, dir).run(); + 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... } @@ -103,7 +106,7 @@ public void tests() throws IOException, InterruptedException, ExecutionException runTest(dir); Assert.assertFalse("Expecting exception", this.isBadTest); } - catch (ScribbleException e) + catch (ScribException e) { Assert.assertTrue("Unexpected exception '" + e.getMessage() + "'", this.isBadTest); } 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 index 69428ba26..42fb6de49 100644 --- a/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test01.scr +++ b/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test01.scr @@ -1,3 +1,5 @@ +//$ 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; 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 index bcd9a2308..f2669e6b1 100644 --- a/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test06.scr +++ b/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test06.scr @@ -1,3 +1,5 @@ +//$ bin/scribblec.sh scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test06.scr + module bad.efsm.grecursion.unfair.Test06; 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 index f5ee7a5a0..16750ac7d 100644 --- a/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test11b.scr +++ b/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test11b.scr @@ -1,3 +1,5 @@ +//$ 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; diff --git a/scribble-test/src/test/resources/bad/liveness/messagelive/Test01.scr b/scribble-test/src/test/resources/bad/liveness/messagelive/Test01.scr index d57369c91..7090e7ab0 100644 --- a/scribble-test/src/test/resources/bad/liveness/messagelive/Test01.scr +++ b/scribble-test/src/test/resources/bad/liveness/messagelive/Test01.scr @@ -1,3 +1,5 @@ +//$ bin/scribblec.sh -ip scribble-test/src/test/resources scribble-test/src/test/resources/bad/liveness/messagelive/Test01.scr + module bad.liveness.messagelive.Test01; 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 index d40b82d09..24414f745 100644 --- a/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test06.scr +++ b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test06.scr @@ -1,3 +1,5 @@ +//$ bin/scribblec.sh scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test06.scr + module bad.liveness.roleprog.unfair.Test06; 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 index 81b31a8e4..a3965c9ae 100644 --- a/scribble-test/src/test/resources/bad/reach/globals/gdo/Test01b.scr +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test01b.scr @@ -1,7 +1,8 @@ module bad.reach.globals.gdo.Test01b; -aux global protocol Proto1(role A, role B) +//aux +global protocol Proto1(role A, role B) { 1() from A to B; do Proto1(A, B); 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 index 0bc0a6f9f..5f129d9ed 100644 --- a/scribble-test/src/test/resources/bad/reach/globals/gdo/Test02a.scr +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test02a.scr @@ -8,7 +8,8 @@ global protocol Proto1(role A, role B) //3() from A to B; } -aux global protocol Proto2(role C, role D) +//aux +global protocol Proto2(role C, role D) { 2() from C to D; do Proto2(C, D); 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/grecursion/Recursion19b.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion19b.scr deleted file mode 100644 index 8dbdb1055..000000000 --- a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion19b.scr +++ /dev/null @@ -1,19 +0,0 @@ -module bad.reach.globals.grecursion.Recursion19b; - - -global protocol Proto1(role A, role B) -{ - rec X - { - choice at A - { - continue X; - } - 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/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/good/efsm/gchoice/Test09.scr b/scribble-test/src/test/resources/good/efsm/gchoice/Test09.scr index 2b5b86816..c67f743bb 100644 --- a/scribble-test/src/test/resources/good/efsm/gchoice/Test09.scr +++ b/scribble-test/src/test/resources/good/efsm/gchoice/Test09.scr @@ -1,3 +1,5 @@ +//$ bin/scribblec.sh scribble-test/src/test/resources/good/efsm/gchoice/Test09.scr + module good.efsm.gchoice.Test09; 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 index 6454e8f24..ba6f3a0eb 100644 --- a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test01a.scr +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test01a.scr @@ -9,7 +9,7 @@ global protocol Proto1(role A, role B) 1() from A to B; choice at A { - continue X; // Not "isomorphic" to a single continue X, because non-det not bisim equiv (cf. language equiv) -- so no "syntatic collapse" to single case + 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 { diff --git a/scribble-test/src/test/resources/good/efsm/grecursion/Test09.scr b/scribble-test/src/test/resources/good/efsm/grecursion/Test09.scr index 2a51a4800..901da6aaa 100644 --- a/scribble-test/src/test/resources/good/efsm/grecursion/Test09.scr +++ b/scribble-test/src/test/resources/good/efsm/grecursion/Test09.scr @@ -1,3 +1,6 @@ +//$ bin/scribblec.sh scribble-test/src/test/resources/good/efsm/grecursion/Test09.scr -project Proto1 C + + module good.efsm.grecursion.Test09; diff --git a/scribble-test/src/test/resources/good/misc/imports/Import01.scr b/scribble-test/src/test/resources/good/misc/imports/Import01.scr index 59236bf3b..6a483c7d4 100644 --- a/scribble-test/src/test/resources/good/misc/imports/Import01.scr +++ b/scribble-test/src/test/resources/good/misc/imports/Import01.scr @@ -1,6 +1,8 @@ //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; diff --git a/scribble-test/src/test/resources/good/misc/imports/Import08.scr b/scribble-test/src/test/resources/good/misc/imports/Import08.scr index a99c2153f..18c60d80d 100644 --- a/scribble-test/src/test/resources/good/misc/imports/Import08.scr +++ b/scribble-test/src/test/resources/good/misc/imports/Import08.scr @@ -1,6 +1,8 @@ //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; 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 index 23e2f7a26..bee832f00 100644 --- a/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion08a.scr +++ b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion08a.scr @@ -18,4 +18,3 @@ global protocol Recursion8a(role A, role B, role C, role D) } l3() from C to D; } - 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 index 9272a17c8..fb8d1507c 100644 --- a/scribble-test/src/test/resources/good/syntax/disamb/imports/Import01.scr +++ b/scribble-test/src/test/resources/good/syntax/disamb/imports/Import01.scr @@ -1,3 +1,5 @@ +//$ 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; 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 index cc796ec5f..6d565efcc 100644 --- a/scribble-test/src/test/resources/good/syntax/disamb/imports/Import01a.scr +++ b/scribble-test/src/test/resources/good/syntax/disamb/imports/Import01a.scr @@ -1,3 +1,5 @@ +// 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; diff --git a/scribble-test/src/test/resources/good/syntax/projroledeclfix/Test01.scr b/scribble-test/src/test/resources/good/syntax/projroledeclfix/Test01.scr index da73b0485..10cff809e 100644 --- a/scribble-test/src/test/resources/good/syntax/projroledeclfix/Test01.scr +++ b/scribble-test/src/test/resources/good/syntax/projroledeclfix/Test01.scr @@ -1,4 +1,4 @@ -//$ bin/scribblec.sh modules/cli/src/test/resources/good/projroledeclfix/Test01.scr -project Bar F +//$ bin/scribblec.sh scribble-test/src/test/resources/good/syntax/projroledeclfix/Test01.scr -project Bar F module good.syntax.projroledeclfix.Test01; 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 index d8ed58124..8f63e0657 100644 --- a/scribble-test/src/test/resources/good/wfchoice/gdo/params/Test02.scr +++ b/scribble-test/src/test/resources/good/wfchoice/gdo/params/Test02.scr @@ -1,3 +1,6 @@ +//$ bin/scribblec.sh scribble-test/src/test/resources/good/wfchoice/gdo/Test02.scr -project Foo A + + module good.wfchoice.gdo.params.Test02; @@ -15,7 +18,6 @@ global protocol Foo(role A, role B) } } - aux global protocol Bar(role C, role D) { M from C to D; diff --git a/scribble-test/src/test/resources/scribble/examples/GMessage.scr b/scribble-test/src/test/resources/scribble/examples/GMessage.scr index 9296dc6cd..c2644017f 100644 --- a/scribble-test/src/test/resources/scribble/examples/GMessage.scr +++ b/scribble-test/src/test/resources/scribble/examples/GMessage.scr @@ -1,9 +1,9 @@ module scribble.examples.GMessage; -global protocol GMessageProtocol(role Buyer,role Seller) { - buy(Order,Customer) from Buyer to Seller; - buy(Order,Customer) from Buyer to Seller; - buy(o:Order,c:Customer) from Buyer to 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; + +global protocol GMessageProtocol(role Buyer, role Seller) { + buy(Order, Customer) from Buyer to Seller; buy(Order) from Buyer to Seller; - buy(ord: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 index 5e23ce411..ec23f7934 100644 --- a/scribble-test/src/test/resources/scribble/examples/Imports.scr +++ b/scribble-test/src/test/resources/scribble/examples/Imports.scr @@ -2,5 +2,6 @@ module scribble.examples.Imports; import scribble.examples.GMessage; -global protocol ImportsProtocol(role Buyer,role Seller) { +global protocol ImportsProtocol(role Buyer, role Seller) { + do GMessage.GMessageProtocol(Buyer, Seller); } diff --git a/scribble-core/src/test/scrib/demo/fase17/intro/FirstL.scr b/scribble-test/src/test/scrib/demo/fase17/intro/FirstL.scr similarity index 100% rename from scribble-core/src/test/scrib/demo/fase17/intro/FirstL.scr rename to scribble-test/src/test/scrib/demo/fase17/intro/FirstL.scr diff --git a/scribble-core/src/test/scrib/demo/fase17/intro/FirstR.scr b/scribble-test/src/test/scrib/demo/fase17/intro/FirstR.scr similarity index 100% rename from scribble-core/src/test/scrib/demo/fase17/intro/FirstR.scr rename to scribble-test/src/test/scrib/demo/fase17/intro/FirstR.scr diff --git a/scribble-core/src/test/scrib/demo/fase17/overview/P1.scr b/scribble-test/src/test/scrib/demo/fase17/overview/P1.scr similarity index 100% rename from scribble-core/src/test/scrib/demo/fase17/overview/P1.scr rename to scribble-test/src/test/scrib/demo/fase17/overview/P1.scr diff --git a/scribble-core/src/test/scrib/demo/fase17/travel/TravelA.java b/scribble-test/src/test/scrib/demo/fase17/travel/TravelA.java similarity index 76% rename from scribble-core/src/test/scrib/demo/fase17/travel/TravelA.java rename to scribble-test/src/test/scrib/demo/fase17/travel/TravelA.java index e6bdc43c8..ce758b1da 100644 --- a/scribble-core/src/test/scrib/demo/fase17/travel/TravelA.java +++ b/scribble-test/src/test/scrib/demo/fase17/travel/TravelA.java @@ -22,17 +22,18 @@ import java.io.IOException; -import org.scribble.main.ScribbleRuntimeException; -import org.scribble.runtime.net.Buf; -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.ExplicitEndpoint; +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.channels.A.EndSocket; -import demo.fase17.travel.TravelAgent.TravelAgent.channels.A.TravelAgent_A_1; -import demo.fase17.travel.TravelAgent.TravelAgent.channels.A.TravelAgent_A_2_Cases; +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 @@ -51,7 +52,7 @@ public void run() throws Exception .accept(C, ss) .branch(C)); } - catch (ScribbleRuntimeException | IOException | ClassNotFoundException e) + catch (ScribRuntimeException | IOException | ClassNotFoundException e) { e.printStackTrace(); } 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-core/src/test/scrib/demo/fase17/travel/TravelC.java b/scribble-test/src/test/scrib/demo/fase17/travel/TravelC.java similarity index 75% rename from scribble-core/src/test/scrib/demo/fase17/travel/TravelC.java rename to scribble-test/src/test/scrib/demo/fase17/travel/TravelC.java index b3372da2d..bd6d62444 100644 --- a/scribble-core/src/test/scrib/demo/fase17/travel/TravelC.java +++ b/scribble-test/src/test/scrib/demo/fase17/travel/TravelC.java @@ -22,14 +22,18 @@ import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.quote; import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.accpt; -import org.scribble.net.Buf; -import org.scribble.net.ObjectStreamFormatter; -import org.scribble.net.session.ExplicitEndpoint; -import org.scribble.net.session.SocketChannelEndpoint; +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.channels.C.TravelAgent_C_1; -import demo.fase17.travel.TravelAgent.TravelAgent.channels.C.TravelAgent_C_2; +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 @@ -43,7 +47,7 @@ public void run() throws Exception { Buf b = new Buf<>(); TravelAgent_C_2 C2 = new TravelAgent_C_1(se) - .connect(A, SocketChannelEndpoint::new, "localhost", 8888); + .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++) @@ -51,7 +55,7 @@ public void run() throws Exception C2 = C2.send(A, query, queries[i]).receive(A, quote, b); } - C2.connect(S, SocketChannelEndpoint::new, "localhost", 9999) + C2.request(S, SocketChannelEndpoint::new, "localhost", 9999) .send(S, payment, "efgh") .receive(S, confirm, b) .send(A, accpt, b.val); // Forward payment ref number diff --git a/scribble-core/src/test/scrib/demo/fase17/travel/TravelS.java b/scribble-test/src/test/scrib/demo/fase17/travel/TravelS.java similarity index 75% rename from scribble-core/src/test/scrib/demo/fase17/travel/TravelS.java rename to scribble-test/src/test/scrib/demo/fase17/travel/TravelS.java index eaba014c5..3bcf5d94a 100644 --- a/scribble-core/src/test/scrib/demo/fase17/travel/TravelS.java +++ b/scribble-test/src/test/scrib/demo/fase17/travel/TravelS.java @@ -20,16 +20,18 @@ 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.ExplicitEndpoint; +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.channels.S.TravelAgent_S_1; +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 { @@ -51,7 +53,7 @@ public void run() throws Exception System.out.println("(S) payment: " + b.val); } - catch (ScribbleRuntimeException | IOException | ClassNotFoundException e) + catch (ScribRuntimeException | IOException | ClassNotFoundException e) { e.printStackTrace(); } diff --git a/scribble-core/src/test/scrib/demo/fase17/travel2/Travel2A.java b/scribble-test/src/test/scrib/demo/fase17/travel2/Travel2A.java similarity index 75% rename from scribble-core/src/test/scrib/demo/fase17/travel2/Travel2A.java rename to scribble-test/src/test/scrib/demo/fase17/travel2/Travel2A.java index faeee60a5..65a28fb63 100644 --- a/scribble-core/src/test/scrib/demo/fase17/travel2/Travel2A.java +++ b/scribble-test/src/test/scrib/demo/fase17/travel2/Travel2A.java @@ -24,18 +24,19 @@ 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.ExplicitEndpoint; -import org.scribble.net.session.SocketChannelEndpoint; +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.channels.A.EndSocket; -import demo.fase17.travel2.TravelAgent2.TravelAgent2.channels.A.TravelAgent2_A_1; -import demo.fase17.travel2.TravelAgent2.TravelAgent2.channels.A.TravelAgent2_A_2_Cases; +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 @@ -54,7 +55,7 @@ public void run() throws Exception .accept(C, ss) .branch(C)); } - catch (ScribbleRuntimeException | IOException | ClassNotFoundException e) + catch (ScribRuntimeException | IOException | ClassNotFoundException e) { e.printStackTrace(); } @@ -70,7 +71,7 @@ private EndSocket run(TravelAgent2_A_2_Cases A2) throws Exception 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).connect(S, SocketChannelEndpoint::new, "localhost", 9999) + 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); 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-core/src/test/scrib/demo/fase17/travel2/Travel2S.java b/scribble-test/src/test/scrib/demo/fase17/travel2/Travel2S.java similarity index 76% rename from scribble-core/src/test/scrib/demo/fase17/travel2/Travel2S.java rename to scribble-test/src/test/scrib/demo/fase17/travel2/Travel2S.java index 2f6f57c43..6b684cd74 100644 --- a/scribble-core/src/test/scrib/demo/fase17/travel2/Travel2S.java +++ b/scribble-test/src/test/scrib/demo/fase17/travel2/Travel2S.java @@ -21,15 +21,16 @@ 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.ExplicitEndpoint; +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.channels.S.TravelAgent2_S_1; +import demo.fase17.travel2.TravelAgent2.TravelAgent2.statechans.S.TravelAgent2_S_1; import demo.fase17.travel2.TravelAgent2.TravelAgent2.roles.S; public class Travel2S @@ -49,12 +50,12 @@ public void run() throws Exception new TravelAgent2_S_1(se) .accept(A, ss) .send(A, port, 7777) - .accept(C, ss2) // FIXME: accept message + .accept(C, ss2) // TODO: API gen accept message/payload ("payment") .send(C, confirm, 4567); System.out.println("(S) payment: " + b.val); } - catch (ScribbleRuntimeException | IOException e) + catch (ScribRuntimeException | IOException e) { e.printStackTrace(); } 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-core/src/test/scrib/demo/supplierinfo/SupplierInfoExplicit.scr b/scribble-test/src/test/scrib/demo/supplierinfo/SupplierInfoExplicit.scr similarity index 98% rename from scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoExplicit.scr rename to scribble-test/src/test/scrib/demo/supplierinfo/SupplierInfoExplicit.scr index 1f34b8e37..f431eb65f 100644 --- a/scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoExplicit.scr +++ b/scribble-test/src/test/scrib/demo/supplierinfo/SupplierInfoExplicit.scr @@ -14,6 +14,7 @@ type "..." from "...xsd" as usercontext; type "..." from "...xsd" as filters; +// Needs -fair -- cf. SupplierInfoNoFair explicit global protocol InfoAuth ( role Client, diff --git a/scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoNoFair.scr b/scribble-test/src/test/scrib/demo/supplierinfo/SupplierInfoNoFair.scr similarity index 85% rename from scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoNoFair.scr rename to scribble-test/src/test/scrib/demo/supplierinfo/SupplierInfoNoFair.scr index 8a70da527..ea093745d 100644 --- a/scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoNoFair.scr +++ b/scribble-test/src/test/scrib/demo/supplierinfo/SupplierInfoNoFair.scr @@ -4,14 +4,14 @@ module src.SupplierInfoNoFair; -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; +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; -type "..." from "...xsd" as usercontext; -type "..." from "...xsd" as filters; +data "..." from "...xsd" as usercontext; +data "..." from "...xsd" as filters; explicit global protocol InfoAuth @@ -29,7 +29,7 @@ explicit global protocol InfoAuth choice at LoginSvc { loginfailure() from LoginSvc to Client; - //disconnect Client and LoginSvc; + //disconnect Client and LoginSvc; // Increases state space somewhat } or { diff --git a/scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfo.scr b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfo.scr similarity index 100% rename from scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfo.scr rename to scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfo.scr diff --git a/scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoBasic.scr b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoBasic.scr similarity index 100% rename from scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoBasic.scr rename to scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoBasic.scr diff --git a/scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoDemo.scr b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoDemo.scr similarity index 100% rename from scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoDemo.scr rename to scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoDemo.scr diff --git a/scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoExper.scr b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoExper.scr similarity index 100% rename from scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoExper.scr rename to scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoExper.scr diff --git a/scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoNoFairBeta.scr b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoNoFairBeta.scr similarity index 100% rename from scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoNoFairBeta.scr rename to scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoNoFairBeta.scr diff --git a/scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoOrig.scr b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoOrig.scr similarity index 100% rename from scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoOrig.scr rename to scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoOrig.scr diff --git a/scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoSubprot.scr b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoSubprot.scr similarity index 100% rename from scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoSubprot.scr rename to scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoSubprot.scr diff --git a/scribble-core/src/test/scrib/exercise/calculator/Client.java b/scribble-test/src/test/scrib/exercise/calculator/Client.java similarity index 100% rename from scribble-core/src/test/scrib/exercise/calculator/Client.java rename to scribble-test/src/test/scrib/exercise/calculator/Client.java diff --git a/scribble-core/src/test/scrib/exercise/calculator/EProtocol.scr b/scribble-test/src/test/scrib/exercise/calculator/EProtocol.scr similarity index 100% rename from scribble-core/src/test/scrib/exercise/calculator/EProtocol.scr rename to scribble-test/src/test/scrib/exercise/calculator/EProtocol.scr diff --git a/scribble-core/src/test/scrib/exercise/calculator/Server.java b/scribble-test/src/test/scrib/exercise/calculator/Server.java similarity index 100% rename from scribble-core/src/test/scrib/exercise/calculator/Server.java rename to scribble-test/src/test/scrib/exercise/calculator/Server.java diff --git a/scribble-core/src/test/scrib/exercise/voting/EProtocol.scr b/scribble-test/src/test/scrib/exercise/voting/EProtocol.scr similarity index 100% rename from scribble-core/src/test/scrib/exercise/voting/EProtocol.scr rename to scribble-test/src/test/scrib/exercise/voting/EProtocol.scr diff --git a/scribble-core/src/test/scrib/exercise/voting/Server.java b/scribble-test/src/test/scrib/exercise/voting/Server.java similarity index 100% rename from scribble-core/src/test/scrib/exercise/voting/Server.java rename to scribble-test/src/test/scrib/exercise/voting/Server.java diff --git a/scribble-core/src/test/scrib/exercise/voting/Voter.java b/scribble-test/src/test/scrib/exercise/voting/Voter.java similarity index 100% rename from scribble-core/src/test/scrib/exercise/voting/Voter.java rename to scribble-test/src/test/scrib/exercise/voting/Voter.java diff --git a/scribble-core/src/test/scrib/scratch/scratch1/MyC.java b/scribble-test/src/test/scrib/scratch/scratch1/MyC.java similarity index 100% rename from scribble-core/src/test/scrib/scratch/scratch1/MyC.java rename to scribble-test/src/test/scrib/scratch/scratch1/MyC.java diff --git a/scribble-core/src/test/scrib/scratch/scratch1/MyS.java b/scribble-test/src/test/scrib/scratch/scratch1/MyS.java similarity index 100% rename from scribble-core/src/test/scrib/scratch/scratch1/MyS.java rename to scribble-test/src/test/scrib/scratch/scratch1/MyS.java diff --git a/scribble-core/src/test/scrib/scratch/scratch1/Scratch1.scr b/scribble-test/src/test/scrib/scratch/scratch1/Scratch1.scr similarity index 100% rename from scribble-core/src/test/scrib/scratch/scratch1/Scratch1.scr rename to scribble-test/src/test/scrib/scratch/scratch1/Scratch1.scr diff --git a/scribble-core/src/test/scrib/test/foo/Foo.scr b/scribble-test/src/test/scrib/test/foo/Foo.scr similarity index 100% rename from scribble-core/src/test/scrib/test/foo/Foo.scr rename to scribble-test/src/test/scrib/test/foo/Foo.scr diff --git a/scribble-core/src/test/scrib/test/foo/MyA.java b/scribble-test/src/test/scrib/test/foo/MyA.java similarity index 100% rename from scribble-core/src/test/scrib/test/foo/MyA.java rename to scribble-test/src/test/scrib/test/foo/MyA.java diff --git a/scribble-core/src/test/scrib/test/foo/MyBC.java b/scribble-test/src/test/scrib/test/foo/MyBC.java similarity index 100% rename from scribble-core/src/test/scrib/test/foo/MyBC.java rename to scribble-test/src/test/scrib/test/foo/MyBC.java 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-core/src/test/scrib/test/test1/Test1.scr b/scribble-test/src/test/scrib/test/test1/Test1.scr similarity index 85% rename from scribble-core/src/test/scrib/test/test1/Test1.scr rename to scribble-test/src/test/scrib/test/test1/Test1.scr index ea763f915..3c11f8f03 100644 --- a/scribble-core/src/test/scrib/test/test1/Test1.scr +++ b/scribble-test/src/test/scrib/test/test1/Test1.scr @@ -1,6 +1,6 @@ //http://sandbox.kidstrythisathome.com/erdos/ -//$ bin/scribblec.sh modules/core/src/test/scrib/test/test1/Test1.scr -ip modules/core/src/test/scrib/ -d modules/core/src/test/scrib/ -session Proto1 -api Proto1 C -V +//$ 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; 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-core/src/test/scrib/tmp/Betty.scr b/scribble-test/src/test/scrib/tmp/Betty.scr similarity index 100% rename from scribble-core/src/test/scrib/tmp/Betty.scr rename to scribble-test/src/test/scrib/tmp/Betty.scr diff --git a/scribble-core/src/test/scrib/tmp/Demo.scr b/scribble-test/src/test/scrib/tmp/Demo.scr similarity index 100% rename from scribble-core/src/test/scrib/tmp/Demo.scr rename to scribble-test/src/test/scrib/tmp/Demo.scr diff --git a/scribble-core/src/test/scrib/tmp/ExpConn.scr b/scribble-test/src/test/scrib/tmp/ExpConn.scr similarity index 100% rename from scribble-core/src/test/scrib/tmp/ExpConn.scr rename to scribble-test/src/test/scrib/tmp/ExpConn.scr diff --git a/scribble-core/src/test/scrib/tmp/Fixme.scr b/scribble-test/src/test/scrib/tmp/Fixme.scr similarity index 100% rename from scribble-core/src/test/scrib/tmp/Fixme.scr rename to scribble-test/src/test/scrib/tmp/Fixme.scr diff --git a/scribble-core/src/test/scrib/tmp/Quirk.scr b/scribble-test/src/test/scrib/tmp/Quirk.scr similarity index 100% rename from scribble-core/src/test/scrib/tmp/Quirk.scr rename to scribble-test/src/test/scrib/tmp/Quirk.scr 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-core/src/test/scrib/tmp/Test2.scr b/scribble-test/src/test/scrib/tmp/Test2.scr similarity index 100% rename from scribble-core/src/test/scrib/tmp/Test2.scr rename to scribble-test/src/test/scrib/tmp/Test2.scr diff --git a/travis/publish.sh b/travis/publish.sh index 43c60b44e..c4f841d1f 100755 --- a/travis/publish.sh +++ b/travis/publish.sh @@ -45,20 +45,20 @@ check_travis_branch_equals_travis_tag() { } 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 + 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 '\[') + 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 @@ -68,7 +68,7 @@ is_release_commit() { } release_version() { - echo "${TRAVIS_TAG}" | sed 's/^release-//' + echo "${TRAVIS_TAG}" | sed 's/^release-//' } safe_checkout_master() { @@ -94,7 +94,7 @@ if ! is_pull_request && build_started_by_tag; then check_release_tag fi -./mvnw install -nsu +./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 @@ -102,16 +102,16 @@ if is_pull_request; then # 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 + #./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 -