Generation.jadd 13.7 KB
Newer Older
René Schöne's avatar
René Schöne committed
1
2
3
4
5
6
7
8
9
10
aspect GenerationUtils {
  public static final String ASTNode.aspectIndent = "  ";

  public String ASTNode.ind(int n) {
    StringBuilder s = new StringBuilder();
    for (int i = 0; i < n; i++) {
      s.append(aspectIndent);
    }
    return s.toString();
  }
René Schöne's avatar
René Schöne committed
11
12
13
14
15
16
17
18
19
20
21

  // --- prettyPrint ---
  syn String MappingDefinitionType.prettyPrint();
  eq JavaMappingDefinitionType.prettyPrint() = getType().getName();
  eq JavaArrayMappingDefinitionType.prettyPrint() = getType().getName() + "[]";

  syn String JavaTypeUse.prettyPrint() {
    StringBuilder sb = new StringBuilder();
    generateAbstractGrammar(sb);
    return sb.toString();
  }
René Schöne's avatar
René Schöne committed
22
23
24
}

aspect AspectGeneration {
25
26
  syn String TokenComponent.internalName() = getDependencySourceDefinitionList().isEmpty() ? externalName() : "_internal_" + getName();
  syn String TokenComponent.externalName() = getName();
René Schöne's avatar
René Schöne committed
27
28
29
30
31
32
33
34
35
36
37
38
39

  // naming convention attributes
  syn String TokenUpdateDefinition.connectMethod() = "connect" + getToken().getName();
  syn String WriteToMqttDefinition.writeTopic() = "_topic_" + getToken().getName();
  syn String WriteToMqttDefinition.lastValue() = "_lastValue" + getToken().getName();
  syn String WriteToMqttDefinition.updateMethod() = "_update_" + getToken().getName();
  syn String WriteToMqttDefinition.writeMethod() = "_writeLastValue_" + getToken().getName();
  syn String WriteToMqttDefinition.tokenResetMethod() = "get" + getToken().getName() + "_reset";
  syn String MappingDefinition.methodName() = "_apply_" + getID();
  syn String DependencyDefinition.dependencyMethod() = "add" +
    Character.toUpperCase(getID().charAt(0)) +
    getID().substring(1);
  syn String DependencyDefinition.internalRelationPrefix() = "_internal_" + getID();
40
  syn String DependencyDefinition.internalTokenName() = getSource().internalName();
René Schöne's avatar
René Schöne committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54

  inh String UpdateDefinition.mqttUpdaterAttribute();
  inh String MappingDefinition.mqttUpdaterAttribute();
  inh String DependencyDefinition.mqttUpdaterAttribute();
  eq Ros2Rag.getChild().mqttUpdaterAttribute() = mqttUpdaterAttribute();
  syn String Ros2Rag.mqttUpdaterAttribute() = "_mqttUpdater";
  syn String Ros2Rag.mqttUpdaterField() = "_mqttUpdater";

  syn String Ros2Rag.mqttSetHostMethod() = "MqttSetHost";
  syn String Ros2Rag.mqttWaitUntilReadyMethod() = "MqttWaitUntilReady";
  syn String Ros2Rag.mqttCloseMethod() = "MqttCloseConnections";

  public String Ros2Rag.generateAspect(String rootNodeName) {
    StringBuilder sb = new StringBuilder();
55
56
    rootNode = getProgram().resolveTypeDecl(rootNodeName);
    generateMqttAspect(sb);
René Schöne's avatar
René Schöne committed
57
58
59
60
    generateGrammarExtension(sb);
    return sb.toString();
  }

61
62
63
64
65
66
67
68
69
70
71
72
73
74
  public void Ros2Rag.generateMqttAspect(StringBuilder sb) {
    org.jastadd.tinytemplate.TinyTemplate tt;
    try {
      tt = new org.jastadd.tinytemplate.TinyTemplate();
      tt.loadTemplates(Ros2Rag.class.getClassLoader().getResourceAsStream("mqtt.tt"));
    } catch (org.jastadd.tinytemplate.TemplateParser.SyntaxError e) {
      e.printStackTrace();
      return;
    }
    org.jastadd.tinytemplate.SimpleContext context = new org.jastadd.tinytemplate.SimpleContext(tt, this);
    context.bind("rootNodeName", rootNode.getName());
    context.bind("RootTypeChildrenMqtt", emitRootTypeChildrenMqtt(tt));
    context.expand(context, "Ros2Rag.mqtt", sb);
  }
René Schöne's avatar
René Schöne committed
75

76
77
78
79
  public String Ros2Rag.emitRootTypeChildrenMqtt(org.jastadd.tinytemplate.TinyTemplate tt) {
    StringBuilder sb = new StringBuilder();
    org.jastadd.tinytemplate.SimpleContext context = new org.jastadd.tinytemplate.SimpleContext(tt, this);
    context.bind("rootNodeName", rootNode.getName());
René Schöne's avatar
René Schöne committed
80
81
    for (Component child : rootNode.getComponentList()) {
      if (child.isTypeComponent()) {
82
83
        context.bind("Name", child.getName());
        context.expand(context, "TypeComponent.mqtt", sb);
René Schöne's avatar
René Schöne committed
84
85
      }
    }
86
    return sb.toString();
René Schöne's avatar
René Schöne committed
87
88
89
  }

  public void Ros2Rag.generateGrammarExtension(StringBuilder sb) {
René Schöne's avatar
René Schöne committed
90
    sb.append("aspect ROS2RAG {\n");
René Schöne's avatar
René Schöne committed
91
92
93
94

    for (UpdateDefinition def : getUpdateDefinitionList()) {
      def.generateAspect(sb);
    }
95
    for (MappingDefinition def : allMappingDefinitions()) {
René Schöne's avatar
René Schöne committed
96
97
98
99
100
      def.generateAspect(sb);
    }
    for (DependencyDefinition def : getDependencyDefinitionList()) {
      def.generateAspect(sb);
    }
René Schöne's avatar
René Schöne committed
101
102
103
    for (TokenComponent token : getProgram().allTokenComponents()) {
      token.generateAspect(sb);
    }
René Schöne's avatar
René Schöne committed
104
105
106
107
108
109
110
111
112
113

    sb.append("}\n");
  }

  abstract void UpdateDefinition.generateAspect(StringBuilder sb);

  String TokenUpdateDefinition.generateMappingApplication(StringBuilder sb, int indent,
      String initialInputVariableName) {
    final String resultVariablePrefix = "result";  // we do not need "_" here, because methodName begins with one
    String inputVariableName = initialInputVariableName;
114
    // last variable need to be declared before begin of try
115
    MappingDefinition lastDefinition = effectiveMappings().get(effectiveMappings().size() - 1);
116
117
118
    sb.append(ind(indent)).append(lastDefinition.getToType().prettyPrint()).append(" ")
      .append(resultVariablePrefix).append(lastDefinition.methodName()).append(";\n");
    sb.append(ind(indent)).append("try {\n");
119
    for (MappingDefinition mappingDefinition : effectiveMappings()) {
René Schöne's avatar
René Schöne committed
120
      String resultVariableName = resultVariablePrefix + mappingDefinition.methodName();
121
122
123
124
125
      sb.append(ind(indent + 1));
      if (mappingDefinition != lastDefinition) {
        sb.append(mappingDefinition.getToType().prettyPrint()).append(" ");
      }
      sb.append(resultVariablePrefix).append(mappingDefinition.methodName())
René Schöne's avatar
René Schöne committed
126
127
128
129
        .append(" = ").append(mappingDefinition.methodName()).append("(")
        .append(inputVariableName).append(");\n");
      inputVariableName = resultVariableName;
    }
130
131
132
133
    sb.append(ind(indent)).append("} catch (Exception e) {\n");
    sb.append(ind(indent + 1)).append("e.printStackTrace();\n");
    sb.append(ind(indent + 1)).append(preemptiveReturnStatement()).append("\n");
    sb.append(ind(indent)).append("}\n");
René Schöne's avatar
René Schöne committed
134
    if (!getAlwaysApply()) {
135
      sb.append(ind(indent)).append("if (").append(preemptiveExpectedValue());
René Schöne's avatar
René Schöne committed
136
137
      if (getToken().isPrimitiveType()) {
        sb.append(" == ").append(inputVariableName);
138
139
140
      } else if (effectiveMappings().get(effectiveMappings().size() - 1).isDefaultMappingDefinition()) {
        sb.append(" != null && ").append(preemptiveExpectedValue()).append(".equals(")
          .append(inputVariableName).append(")");
René Schöne's avatar
René Schöne committed
141
      } else {
142
        sb.append(" != null ? ").append(preemptiveExpectedValue()).append(".equals(")
René Schöne's avatar
René Schöne committed
143
144
145
146
147
148
149
150
          .append(inputVariableName).append(")").append(" : ")
          .append(inputVariableName).append(" == null");
      }
      sb.append(") { ").append(preemptiveReturnStatement()).append(" }\n");
    }
    return inputVariableName;
  }

151
152
153
154
  syn String TokenUpdateDefinition.preemptiveExpectedValue();
  eq ReadFromMqttDefinition.preemptiveExpectedValue() = "get" + getToken().getName() + "()";
  eq WriteToMqttDefinition.preemptiveExpectedValue() = lastValue();

René Schöne's avatar
René Schöne committed
155
156
157
158
159
160
161
162
163
164
  syn String TokenUpdateDefinition.preemptiveReturnStatement();
  eq ReadFromMqttDefinition.preemptiveReturnStatement() = "return;";
  eq WriteToMqttDefinition.preemptiveReturnStatement() = "return false;";

  @Override
  void ReadFromMqttDefinition.generateAspect(StringBuilder sb) {
    sb.append(ind(1)).append("public void ").append(getToken().containingTypeDecl().getName()).append(".")
      .append(connectMethod()).append("(String topic) {\n");
    sb.append(ind(2)).append(mqttUpdaterAttribute()).append("().newConnection(topic, message -> {\n");
    String lastResult = generateMappingApplication(sb, 3, "message");
165
166
167
168
169
    if (loggingEnabledForReads) {
      sb.append(ind(3)).append("System.out.println(\"[Read] \" + topic + \" -> ")
        .append(getToken().getName()).append(" = \" + ").append(lastResult)
        .append(");\n");
    }
René Schöne's avatar
René Schöne committed
170
    sb.append(ind(3)).append("set").append(getToken().getName()).append("(").append(lastResult).append(");\n");
René Schöne's avatar
René Schöne committed
171
    sb.append(ind(2)).append("});\n");
René Schöne's avatar
René Schöne committed
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
    sb.append(ind(1)).append("}\n\n");
  }

  @Override
  void WriteToMqttDefinition.generateAspect(StringBuilder sb) {
    String parentTypeName = getToken().containingTypeDecl().getName();
    // fields
    sb.append(ind(1)).append("private String ").append(parentTypeName).append(".")
      .append(writeTopic()).append(" = null;\n");
    sb.append(ind(1)).append("private byte[] ").append(parentTypeName).append(".")
      .append(lastValue()).append(" = null;\n");

    // connect method
    sb.append(ind(1)).append("public void ").append(parentTypeName).append(".")
      .append(connectMethod()).append("(String topic, boolean writeCurrentValue) {\n");
    sb.append(ind(2)).append(writeTopic()).append(" = topic;\n");
    sb.append(ind(2)).append(updateMethod()).append("();\n");
    sb.append(ind(2)).append("if (writeCurrentValue) {\n");
    sb.append(ind(3)).append(writeMethod()).append("();\n");
    sb.append(ind(2)).append("}\n");
    sb.append(ind(1)).append("}\n\n");

    // update method
René Schöne's avatar
René Schöne committed
195
    sb.append(ind(1)).append("protected boolean ").append(parentTypeName).append(".")
René Schöne's avatar
René Schöne committed
196
197
198
199
200
201
202
203
      .append(updateMethod()).append("() {\n");
    sb.append(ind(2)).append(tokenResetMethod()).append("();\n");
    String lastResult = generateMappingApplication(sb, 2, "get" + getToken().getName() + "()");
    sb.append(ind(2)).append(lastValue()).append(" = ").append(lastResult).append(";\n");
    sb.append(ind(2)).append("return true;\n");
    sb.append(ind(1)).append("}\n\n");

    // write method
René Schöne's avatar
René Schöne committed
204
    sb.append(ind(1)).append("protected void ").append(parentTypeName).append(".")
René Schöne's avatar
René Schöne committed
205
      .append(writeMethod()).append("() {\n");
206
207
    if (loggingEnabledForWrites) {
      sb.append(ind(2)).append("System.out.println(\"[Write] ").append(getToken().getName())
208
209
210
        .append(" = \" + ")
        .append("get").append(getToken().getName()).append("() + \" -> \" + ")
        .append(writeTopic()).append(");\n");
211
    }
René Schöne's avatar
René Schöne committed
212
213
214
215
216
217
218
219
220
    // _mqttUpdater().publish(${writeTopic()}, ${lastValue()});
    sb.append(ind(2)).append(mqttUpdaterAttribute()).append("().publish(")
      .append(writeTopic()).append(", ").append(lastValue()).append(");\n");
    sb.append(ind(1)).append("}\n\n");
  }

  void MappingDefinition.generateAspect(StringBuilder sb) {
    sb.append(ind(1)).append("protected static ").append(getToType().prettyPrint())
      .append(" ASTNode.").append(methodName()).append("(")
221
222
      .append(getFromType().prettyPrint()).append(" ").append(getFromVariableName())
      .append(") throws Exception {\n");
René Schöne's avatar
René Schöne committed
223
224
225
226
227
228
229
230
231
232
233
234
235
    for (String line : getContent().split("\n")) {
      if (!line.trim().isEmpty()) {
        sb.append(ind(2)).append(line).append("\n");
      }
    }
    sb.append(ind(1)).append("}\n\n");
  }

  void DependencyDefinition.generateAspect(StringBuilder sb) {
    String targetParentTypeName = getTarget().containingTypeDecl().getName();
    String sourceParentTypeName = getSource().containingTypeDecl().getName();

    // dependency method
René Schöne's avatar
René Schöne committed
236
    sb.append(ind(1)).append("public void ").append(targetParentTypeName).append(".")
René Schöne's avatar
René Schöne committed
237
238
239
      .append(dependencyMethod()).append("(").append(sourceParentTypeName).append(" source) {\n");
    sb.append(ind(2)).append("add").append(internalRelationPrefix()).append("Source(source);\n");
    sb.append(ind(1)).append("}\n\n");
René Schöne's avatar
René Schöne committed
240
241
242
243
  }

  void TokenComponent.generateAspect(StringBuilder sb) {
    if (getDependencySourceDefinitionList().isEmpty()) { return; }
René Schöne's avatar
René Schöne committed
244

René Schöne's avatar
René Schöne committed
245
    String parentTypeName = containingTypeDecl().getName();
René Schöne's avatar
René Schöne committed
246
    // virtual setter
René Schöne's avatar
René Schöne committed
247
    sb.append(ind(1)).append("public ").append(parentTypeName).append(" ")
René Schöne's avatar
René Schöne committed
248
249
      .append(parentTypeName).append(".set").append(getName()).append("(")
      .append(getJavaTypeUse().prettyPrint()).append(" value) {\n");
René Schöne's avatar
René Schöne committed
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
    sb.append(ind(2)).append("set").append(internalName()).append("(value);\n");

    for (DependencyDefinition dependencyDefinition : getDependencySourceDefinitionList()) {
      String targetParentTypeName = dependencyDefinition.getTarget().containingTypeDecl().getName();
      sb.append(ind(2)).append("for (").append(targetParentTypeName).append(" target : get")
        .append(dependencyDefinition.internalRelationPrefix()).append("TargetList()) {\n");
      sb.append(ind(3)).append("if (target.")
        .append(dependencyDefinition.targetUpdateDefinition().updateMethod())
        .append("()) {\n");
      sb.append(ind(4)).append("target.")
        .append(dependencyDefinition.targetUpdateDefinition().writeMethod())
        .append("();\n");
      sb.append(ind(3)).append("}\n");
      sb.append(ind(2)).append("}\n");
    }
René Schöne's avatar
René Schöne committed
265
266
267
268
    sb.append(ind(2)).append("return this;\n");
    sb.append(ind(1)).append("}\n\n");

    // virtual getter
René Schöne's avatar
René Schöne committed
269
270
    sb.append(ind(1)).append("public ").append(getJavaTypeUse().prettyPrint())
      .append(" ").append(parentTypeName).append(".get").append(getName()).append("() {\n");
René Schöne's avatar
René Schöne committed
271
    sb.append(ind(2)).append("return get").append(internalName()).append("();\n");
René Schöne's avatar
René Schöne committed
272
273
274
    sb.append(ind(1)).append("}\n\n");
  }
}
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312

aspect RelationGeneration {
  syn java.util.List<Relation> Ros2Rag.additionalRelations() {
    java.util.List<Relation> result = new java.util.ArrayList<>();
    for (DependencyDefinition dd : getDependencyDefinitionList()) {
      result.add(dd.getRelationToCreate());
    }
    return result;
  }

  syn nta Relation DependencyDefinition.getRelationToCreate() {
    BidirectionalRelation result = new BidirectionalRelation();
    NavigableRole left = new ListRole(internalRelationPrefix() + "Source");
    left.setType(getTarget().containingTypeDecl());
    NavigableRole right = new ListRole(internalRelationPrefix() + "Target");
    right.setType(getSource().containingTypeDecl());
    result.setLeft(left);
    result.setRight(right);
    return result;
  }
}

aspect GrammarExtension {
  refine BackendAbstractGrammar public void TokenComponent.generateAbstractGrammar(StringBuilder b) {
    if (getNTA()) {
      b.append("/");
    }
    b.append("<");
    if (!getName().equals("")) {
      b.append(internalName()).append(":");
    }
    getJavaTypeUse().generateAbstractGrammar(b);
    b.append(">");
    if (getNTA()) {
      b.append("/");
    }
  }
}