/
CreateSREWithTinyMAS.spec
3453 lines (3203 loc) · 118 KB
/
CreateSREWithTinyMAS.spec
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* $Id$
*
* SARL is an general-purpose agent programming language.
* More details on http://www.sarl.io
*
* Copyright (C) 2014-2016 the original authors or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sarl.docs.tutorials
import com.google.inject.Inject
import io.sarl.docs.utils.SARLParser
import io.sarl.docs.utils.SARLSpecCreator
import org.jnario.runner.CreateWith
import static extension io.sarl.docs.utils.SpecificationTools.*
import static extension org.junit.Assume.*
import io.sarl.core.Logging
import io.sarl.core.DefaultContextInteractions
import io.sarl.eclipse.runtime.SREConstants
/* @outline
*
* <p>This document describes how to create a SARL Run-time Environment (SRE) with the
* <a href="https://github.com/gallandarakhneorg/tinymas">tinyMAS platform</a>.
*
* <p>SRE executes or interprets compiled SARL code on an "hardware platform."
* The figure below illustrates the compilation process of a SARL program in which the
* run-time environment is involved.
*
* <p>![SARL Generation Process](http://www.sarl.io/images/compilation-process.png)
*
* <p>The Tiny Multiagent Platform (tinyMAS) is a very small software platform, which permits to implement
* and run agent-based systems. This platform was written by Stéphane GALLAND and Nicolas GAUD for the
* multiagent courses of the Computer Science Department of the
* <a href="http://www.utbm.fr">Belfort-Montbéliard University of Technology</a>.
*
* <p>The purpose of this document is to describe the basics steps for making a SRE without
* changing the source code of neither the platform nor the SARL compiler.
* The tinyMAS SRE does not support all the elements of the SARL metamodel. Indeed the support for
* external contexts and inner contexts is not implemented.
*
* <p>Before reading this document, it is recommended reading
* the [General Syntax Reference](../reference/GeneralSyntaxReferenceSpec.html).
*
* <p><div class="bt-download">
* <a href="https://github.com/gallandarakhneorg/tinymas"><img alt="Download the Source Code" src="%website%/images/download-icon.png"/></a>
* </div>
* The elements that are explained in this tutorial are:
*
* * the definition of the concepts from the SARL metamodel linked to the tinyMAS concepts;
* * the definition of the definition of the boot process;
* * the update of the manifest in order to make tinyMAS recognized as a SRE.
*
* <p>The source code related to this tutorial may be found
* in the [tinyMAS Git repository](https://github.com/gallandarakhneorg/tinymas).
*/
@CreateWith(SARLSpecCreator)
describe "Creating a SARL Run-time Environment for the tinyMAS platform"{
@Inject extension SARLParser
/* The SARL language and the tinyMAS platform have been defined based on a collection
* of concepts that are formally described in their respective metamodels.
* This section gives a short overview of the two metamodels, and their possible links.
*
* <p>Defining the links between the SARL metamodel and the metamodel of the SRE is the first
* mandatory point for transforming the targeted platform to SRE.
*/
describe "SARL and tinyMAS metamodels" {
/* The SARL language is based on a collection of concepts that are described into its metamodel.
*
* <p>![Part of the SARL Metamodel](./SARL_metamodel.png)
*
* The key elements in the SARL metamodel are:
*
* * `Context`: defines a set of interaction spaces in which agents are involved.
* * `Space`: or interaction space; defines a space in which interactions may occur.
* * `Address`: defines the identifiers of the agents in the interaction spaces.
* * `EventSpace`: defines a specific interaction space in which agents are interacting by firing and receiving events.
* * `Event`: defines an information/event that is exchanged by agents in an event space.
* * `Capacity`: defines a know-how of the agent; actions defines in a capacity could be invoked by the agent.
* * `Skill`: defines a specific implementation of a capacity. When a capacity's action is invoked by an agent, the corresponding implementation in the skill is called.
* * `Behavior`: defines a sub-part of the agent's behavior.
* * Built-in capacities: the capacities that are known by the agents by default. The corresponding skills are provided by the run-time environment.
*
* @filter(.*)
*/
fact "SARL Metamodel" {
// Test the URLs in the introduction
"http://www.sarl.io/images/compilation-process.png" should beURL "!file"
"http://www.utbm.fr" should beURL "!file"
"https://github.com/gallandarakhneorg/tinymas" should beURL "!file"
"../reference/GeneralSyntaxReferenceSpec.html" should beAccessibleFrom this
// The checks are valid only if the macro replacements were done.
// The replacements are done by Maven.
// So, Eclipse Junit tools do not make the replacements.
System.getProperty("sun.java.command", "").startsWith("org.eclipse.jdt.internal.junit.").assumeFalse
//
"%website%" should beURL "!file"
//
"./SARL_metamodel.png" should beAccessibleFrom this
}
/* The tinyMAS platform is based on a collection of concepts that are described into its metamodel.
*
* <p>![Part of the tinyMAS Metamodel](./tinyMAS_metamodel.png)
*
* The key elements in the tinyMAS metamodel are:
*
* * `AgentIdentifier`: defines the identifiers of the agents.
* * `Agent`: defines the concept of agent. Application agents must be defined in sub-classes.
* * `Message`: defines the base information exchanged by the agents.
* * `MessageTransportService` (and `AgentCommunicationChannel`): define the routing mechanism for the messages.
* * `MailboxManager`: defines a container of received messages for each agent.
* * `WhitePages`: defines a repository of all the agents in the system. It maps the agent identifiers to the agents.
* * `YellowPages`: defines a repository of services that could be provided by the agents. It maps the name of a service to a list of agent identifiers.
* * `Scheduler`: defines the agent execution policy.
* * `Kernel`: represents the entire tinyMAS platform.
* * `KernelListener`: describes an object that could be notified when a specific event occured in the tinyMAS kernel.
*
* @filter(.*)
*/
fact "TinyMAS Metamodel" {
"./tinyMAS_metamodel.png" should beAccessibleFrom this
}
/* The elements to define for creating a SRE are described in the following table.
* This table provides the mapping of these elements (several SARL concepts) to
* the corresponding implementation approach for tinyMAS.
*
* The first column of the table gives the key point to consider for creating a SRE.
* The second column provides the key SARL concepts.
* And the third column describes the basics of the implementation for tinyMAS.
*
* <table><thead>
* <tr><th>SARL Element</th><th>SARL Concept</th><th>tinyMAS Implementation</th></tr>
* </thead><tbody>
* <tr><td>Identifying the agents</td>
* <td>`Address`</td>
* <td>tinyMAS provides the concept of `AgentIdentifier`.
* This identifier contains a reference to the kernel identifier, and
* the UUID of the agent. The SARL Address is for a specific interaction
* space. It contains the space identifier, and the UUID of the agent.
* For making the implementation simple, we assume that there is
* only the SARL default space available. The other spaces will not
* be supported by a tinyMAS implementation.</td></tr>
* <tr><td>Agent abstraction</td>
* <td>`Agent`</td>
* <td>A specific implementation of the tinyMAS `Agent` should be coded.
* This implementation must have a reference to the SARL `Agent`.
* Additionally, the tinyMAS `Agent` will be the place to write
* the support for the agent life-cycle and the built-in capacities.</td></tr>
* <tr><td>Exchanged information format for direct interaction</td>
* <td>`Event`</td>
* <td>The interaction in the tinyMAS platform is based on the concept of `Message`.
* tinyMAS provides all the features for routing and delivering the messages.
* Because the SARL agents are exchanging events by default, the tinyMAS
* cannot be directly delivered to the SARL agents. Linking the `Message`
* and `Event` concepts is done by considering that each `Event` occurrence
* must be enveloped by a `Message`, i.e. the content of a tinyMAS message
* is a SARL event.</td></tr>
* <tr><td>Receiving SARL events</td>
* <td>Behavior units `on`</td>
* <td>A specific module in tinyMAS must be written for invoking the
* SARL behavior units on each SARL event that are in the received
* tinyMAS messages.</td></tr>
* <tr><td>Default context definition</td>
* <td>`Context`</td>
* <td>In SARL, every agent exists in a context, named the default context.
* It is mandatory for tinyMAS to provide an implementation for the
* default context.</td></tr>
* <tr><td>Default space definition</td>
* <td>`EventSpace`</td>
* <td>In SARL, every agent could interact through the default interaction
* space. It is mandatory for tinyMAS to provide an implementation for the
* default space.</td></tr>
* <tr><td>Agent life-cycle</td>
* <td></td>
* <td>The agent life-cycle in tinyMAS is based on the calls to the functions
* `start` for initialization, `live` for running the agent behavior, and
* `end` for destroying the agent.
* The agent life-cycle in SARL is different. It is based on the receiving
* of events. The `Initialize` event represents the initialization of the agent.
* The `Destroy` event represents the agent destruction. The other events
* enable to create the agent behavior.
* Because the tinyMAS agent is the one that will be executed by tinyMAS,
* it is mandatory to generates the SARL events in the three tinyMAS life-cycle
* functions, a.k.a. `start`, `live`, `end`.</td></tr>
* <tr><td>Managing platform events</td>
* <td>`AgentSpawned`, `AgentKilled`</td>
* <td>Several SARL events are assumed to be fired by the SRE. The two events
* that will be supported by tinyMAS are `AgentSpawned` for agent spawning,
* and `AgentKilled` for agent destruction.
* The other SARL platform events are ignored by tinyMAS, e.g. `ContextJoined`,
* `ContextLeft`, `MemberJoined`, `MemberLeft`.</td></tr>
* <tr><td>Agent Spawning</td>
* <td>`spawn` functions</td>
* <td>A specific agent spawning function must be written for creating
* a tinyMAS agent that is embedding a SARL agent definition.
* This spawning functions will be invoked by the built-in capacities
* (see below).</td></tr>
* <tr><td>Built-in capacity implementation</td>
* <td><a href="../reference/BuiltinCapacityReferenceSpec.html">BICs</a></td>
* <td>It is assumed that every SARL agent always contains the skills for a
* specific set of capacities, named the built-in capacities. These
* skills are supposed to be provided by the SRE.
* Consequently, each built-in capacity must have an implementation based
* on the tinyMAS features.</td></tr>
* <tr><td>SRE Booting</td>
* <td></td>
* <td>An utility class for booting the tinyMAS SRE must be provided.
* Usually, this boot class takes the fully qualified name of the
* agent to launch, and the parameters to give to this agent.
* The boot class is supposed to set up the tinyMAS platform for
* being used as a SRE, and to launch SARL agents.</td></tr>
* </tbody></table>
*
* @filter(.*)
*/
fact "Linking the metamodels' concepts" {
"../reference/BuiltInCapacityReferenceSpec.html" should beAccessibleFrom this
}
}
/* `AgentIdentifier` in tinyMAS is based on a UUID and a reference to the identifier of the kernel.
* Because `AgentIdentifier` does not provide a function for retrieving the UUID, we
* should write an utility class for obtaining it.
*
* <p>The `AgentIdentifier` string representation contains the UUID, followed by a column character
* and the kernel identifier.
* <p>This utility class will be used for extracting the UUID of the tinyMAS agent identifier
* in order to create SARL address on the fly.
*
* @filter(.* = '''|'''|.parseSuccessfully.*)
*/
fact "Mapping of the identifiers" {
'''
final class Identifiers {
static def toUUID(aid : AgentIdentifier) : UUID {
val aidstr = aid.toString
val index = aidstr.indexOf(":")
return UUID::fromString(aidstr.substring(0, index))
}
}
'''.parseSuccessfully(
'''
package io.sarl.docs.tutorials.tinyMASSRE
import java.util.UUID
interface AgentIdentifier {}
''',
// TEXT
'''
''')
}
/* A SARL Context defines the boundary of a sub-system, and gathers a collection of interaction Spaces.
* In each context, there is at least one particular space called the default space to which all agents in this
* context belong. This ensures the existence of a common shared space to all agents in the same context.
* <p>Each agent can then create specific public or private spaces to achieve its personal goals.
* Since their creation, agents are incorporated into a context called the default context.
*
* <p>The concept of context is not explicit in tinyMAS, i.e. all agents are evolving in the same and unique
* context.
*
* <p>Because SARL agents require to have access to the instance of the default context, a specific
* implementation must be provided upon the tinyMAS API.
*/
describe "Definition of the default context" {
/* A SARL context must be a class that is implementing the `AgentContext` type
* (provided in the SARL API).
*
* @filter(.* = '''|'''|.parseSuccessfully.*)
*/
fact "Definition of the context class" {
'''
class TMAgentContext implements io.sarl.lang.core.AgentContext {
// The code in the rest of this section will appear here
}
'''.parseSuccessfully(
'''
package io.sarl.docs.tutorials.tinyMASSRE
abstract
''',
// TEXT
'''
''')
}
/* A SARL context must have a unique identifier.
* We assume that only one context, the default context, will exist in
* the SARL applications ran with tinyMAS.
*
* <p>In order to retrieve easy the UUID of the default (root) context,
* we define the identifier as a public constant.
*
* @filter(.* = '''|'''|.parseSuccessfully.*)
*/
fact "Definition of the context identifier" {
'''
public static val TINYMAS_AGENT_CONTEXT_ID = UUID::fromString("cdb0d568-4059-40cf-96c4-d078fee91cb1")
def getID : UUID {
TINYMAS_AGENT_CONTEXT_ID
}
'''.parseSuccessfully(
'''
package io.sarl.docs.tutorials.tinyMASSRE
import java.util.UUID
import io.sarl.lang.core.AgentContext
abstract class TMAgentContext implements AgentContext {
''',
// TEXT
'''
}
''')
}
/* A SARL context has a default interaction space.
*
* <p>We declare the default space in the context class `TMAgentContext`.
* The concrete definition of the default space class named `TMDefaultSpace`
* is done later in this document.
*
* @filter(.* = '''|'''|.parseSuccessfully.*)
*/
fact "Declaration of the default space of the context" {
'''
var defaultSpace : TMDefaultSpace
def getDefaultSpace : EventSpace {
this.defaultSpace
}
'''.parseSuccessfully(
'''
package io.sarl.docs.tutorials.tinyMASSRE
import java.util.UUID
import io.sarl.lang.core.AgentContext
import io.sarl.lang.core.EventSpace
interface TMDefaultSpace extends EventSpace {}
abstract class TMAgentContext implements AgentContext {
''',
// TEXT
'''
}
''')
}
/* A SARL context provides a collection of functions for retrieving the spaces inside the context.
*
* <p>Please note that we assume that only one context will exist in the tinyMAS application.
* This context will be assumed to be the default context.
* In the same way, we assume that only one space (the default space) will exist in the default
* context.
*
* <p>Consequently, the function `getSpace()` replies the collection of all the context as
* an singleton collection instance that is containing the default space.
* This function must reply a auto-synchronized collection. We use the `Collections3` utility
* class, provided in the SARL API, for creating the synchronized collection.
* The first parameter of the `synchronizedCollection` function is the collection to synchronized,
* the second parameter is the object on from which the synchronization token will be obtained.
*
* <p>The `getSpaces(Class)` function is supposed to reply the existing spaces that were created
* by using the given type of space specification.
* Because of our assumption on the space singleton in the context, this function replies
* only the default space if the given space specification type is `EventSpaceSpecification`.
*
* <p>The `getSpace(UUID)` function replies the default space only if the given UUID is the
* identifier of the default space. In the other cases, the function replies nothing.
*
* @filter(.* = '''|'''|.parseSuccessfully.*)
*/
fact "Definition of the getter functions for spaces" {
'''
def getSpaces : SynchronizedCollection<? extends Space> {
Collections3::synchronizedCollection(Collections::singleton(this.defaultSpace), this)
}
def getSpaces(spec : Class<? extends SpaceSpecification<S>>)
: SynchronizedCollection<S>
with S extends Space {
if (spec !== null && spec == typeof(EventSpaceSpecification)) {
return Collections3::synchronizedCollection(Collections::singleton(this.defaultSpace as S), this);
}
return Collections3::synchronizedCollection(Collections::emptyList, this)
}
def getSpace(spaceUUID : UUID) : S
with S extends Space {
if (spaceUUID == this.defaultSpace.spaceID.ID) {
return this.defaultSpace as S
}
return null
}
'''.parseSuccessfully(
'''
package io.sarl.docs.tutorials.tinyMASSRE
import java.util.UUID
import java.util.Collections
import io.sarl.lang.core.AgentContext
import io.sarl.lang.core.Space
import io.sarl.lang.core.SpaceSpecification
import io.sarl.lang.core.EventSpaceSpecification
import io.sarl.lang.util.SynchronizedCollection
import io.sarl.util.Collections3
abstract class TMAgentContext implements AgentContext {
var defaultSpace : Space
''',
// TEXT
'''
}
''')
}
/* The context provides functions for creating spaces.
* Because we assume that no additional space could be created upon the tinyMAS
* SRE implementation, all these functions generates an "unsupported operation"
* exception.
*
* @filter(.* = '''|'''|.parseSuccessfully.*)
*/
fact "Definition of the creation functions for spaces" {
'''
def createSpace(spec : Class<? extends SpaceSpecification<S>>,
spaceUUID : UUID, creationParams : Object*)
: S
with S extends Space {
throw new UnsupportedOperationException
}
def getOrCreateSpaceWithSpec(spec : Class<? extends SpaceSpecification<S>>,
spaceUUID : UUID,creationParams : Object*)
: S
with S extends Space {
throw new UnsupportedOperationException
}
def getOrCreateSpaceWithID(spaceUUID : UUID,
spec : Class<? extends SpaceSpecification<S>>,
creationParams : Object*)
: S
with S extends Space {
throw new UnsupportedOperationException
}
'''.parseSuccessfully(
'''
package io.sarl.docs.tutorials.tinyMASSRE
import java.util.UUID
import io.sarl.lang.core.AgentContext
import io.sarl.lang.core.Space
import io.sarl.lang.core.SpaceSpecification
abstract class TMAgentContext implements AgentContext {
''',
// TEXT
'''
}
''')
}
/* The constructor of the agent context class must be defined for initializing
* the fields of the class.
*
* <p>The instance of the default space must be provided as parameter in order to
* set the `defaultSpace` field.
*
* <p>Additionally, the default space instance must be linked to the context
* (see the definition of the space class below). In the constructor,
* the `setAgentContext` is invoked on the default space.
*
* @filter(.* = '''|'''|.parseSuccessfully.*)
*/
fact "Definition of the constructor" {
'''
new (defaultSpace : TMDefaultSpace) {
this.defaultSpace = defaultSpace
this.defaultSpace.setAgentContext(this);
}
'''.parseSuccessfully(
'''
package io.sarl.docs.tutorials.tinyMASSRE
import java.util.UUID
import io.sarl.lang.core.AgentContext
interface TMDefaultSpace {
def setAgentContext(context : AgentContext)
}
abstract class TMAgentContext implements AgentContext {
var defaultSpace : TMDefaultSpace
''',
// TEXT
'''
}
''')
}
}
/* The default space is the interaction space in which all the agents will be involved.
* Because we assume that only one agent context exists in the system, the default space
* becomes a singleton (only one default space could exist in a context).
*/
describe "Definition of the default space" {
/* A SARL default space must support an event-based interaction mechanism.
* Consequently, the default space class must implement the `EventSpace` interface
* that is provided by the SARL API.
*
* @filter(.* = '''|'''|.parseSuccessfully.*)
*/
fact "Definition of the space class" {
'''
class TMDefaultSpace implements io.sarl.lang.core.EventSpace {
// The code in the rest of this section will appear here
}
'''.parseSuccessfully(
'''
package io.sarl.docs.tutorials.tinyMASSRE
abstract
''',
// TEXT
'''
''')
}
/* A SARL space must have a unique identifier.
* We assume that only one context, the default context, will exist in
* the SARL applications ran with tinyMAS. Consequently, the default
* space instance becomes a singleton.
*
* <p>In order to retrieve easy the UUID of the default (root) context,
* we define the identifier as a public constant.
*
* <p>We defines the function `getSpaceID`, which is replying the space identifier.
*
* <p>The initialization of the `spaceID` field is not discussed yet, because
* the context identifier is mandatory for building the space identifier.
* The space identifier creation is discussed in the following section.
*
* @filter(.* = '''|'''|.parseSuccessfully.*)
*/
fact "Definition of the context identifier" {
'''
public static val TINYMAS_DEFAULT_SPACE_ID = UUID::fromString("1db39309-8be7-4809-ad76-1ede6e792296")
var spaceID : SpaceID
def getSpaceID : SpaceID {
this.spaceID
}
'''.parseSuccessfully(
'''
package io.sarl.docs.tutorials.tinyMASSRE
import java.util.UUID
import io.sarl.lang.core.EventSpace
import io.sarl.lang.core.SpaceID
abstract class TMDefaultSpace implements EventSpace {
''',
// TEXT
'''
}
''')
}
/* We need to have a reference to the agent context that is containing this space in order
* to create the space identifier and to provide a reference to this context from the space.
*
* <p>Firstly, the reference to the agent context is declared as a weak reference field, named
* `context`.
*
* <p>The initialization of the `context` field is done by the `setAgentContext` function.
* As illustrated in the context definition section, this function is invoked when creating
* the agent context in order to be binded to its default space.
*
* <p>The space identifier is initialized in the `setAgentContext` because this is the place
* where the space's UUID and the context's identifier are known.
*
* <p>Finally, the getter function for retrieving the agent context is defined too.
*
* @filter(.* = '''|'''|.parseSuccessfully.*)
*/
fact "Linking the agent context to the space" {
'''
var context : WeakReference<TMAgentContext>
package def setAgentContext(context : TMAgentContext) {
this.context = new WeakReference(context)
this.spaceID = new SpaceID(context.ID, TINYMAS_DEFAULT_SPACE_ID, null)
}
def getAgentContext : TMAgentContext {
this.context.get
}
'''.parseSuccessfully(
'''
package io.sarl.docs.tutorials.tinyMASSRE
import java.util.UUID
import java.lang.ref.WeakReference
import io.sarl.lang.core.EventSpace
import io.sarl.lang.core.SpaceID
interface TMAgentContext {
def getID : UUID
}
abstract class TMDefaultSpace implements EventSpace {
var TINYMAS_DEFAULT_SPACE_ID : UUID
var spaceID : SpaceID
''',
// TEXT
'''
}
''')
}
}
/* The next step is the definition of an abstraction for the SARL agent that could be
* executed as a tinyMAS agent.
* The easiest way to proceed is to create a tinyMAS agent class that has a reference
* to the SARL agent. Then, the specific tinyMAS agent implementation will map all
* the features from the tinyMAS platform to their equivalent features for the SARL agent.
*
*/
describe "First definition of the agent" {
/* We define a specific tinyMAS agent type, which is named `TMSarlAgent`.
* This agent definition contains a reference to the instance of the SARL agent definition,
* in the field `sarlAgent`. The getter of the SARL agent is also defined.
*
* <p>We define the `getID` function in order to easily retrieve the unique identifier of the
* agent. This unique identifier is the identifier of the SARL agent.
*
* <p>A constructor is defined for initializing the `sarlAgent` field.
*
* <caution>The constructor will be refined and redefined in the rest of this document.</caution>
*
* @filter(.* = '''|'''|.parseSuccessfully.*)
*/
fact "SARL Agent inside tinyMAS Agent" {
'''
class TMSarlAgent extends org.arakhne.tinyMAS.core.Agent {
val sarlAgent : io.sarl.lang.core.Agent
protected def getSarlAgent : io.sarl.lang.core.Agent {
this.sarlAgent
}
def getID : UUID {
this.sarlAgent.ID
}
new (sarlAgent : io.sarl.lang.core.Agent) {
this.sarlAgent = sarlAgent
}
}
'''.parseSuccessfully(
'''
package org.arakhne.tinyMAS.core
import java.util.UUID
abstract class Agent {
}
abstract
''',
// TEXT
'''
''')
}
/* Event-based interaction is at the heart of the interaction mechanisms that could
* be used by the SARL agent. The `TMSarlAgent` class must provide tools for
* routing events when the basic interaction mechanism of tinyMAS is based on messages.
*
* <p>The first feature to implement is the firing/routing of SARL event.
* We define the `fireEvent` function that is extracting the SARL agent's behavior units
* (the `on` blocks of code), and is calling them with the event given as parameter.
*
* <p>Retrieving the SARL behavior unit is a algorithm that is following the SARL specifications.
* Fortunately, the SARL API provides an utility class for exploring the Java definition
* of an agent (by using the Java reflection mechanism), and providing the list of the
* behavior units that are taken a given event as input.
* The utility class is named `BehaviorGuardEvaluatorRegistry`. According to the SARL
* API, one instance of this registry may be created for each agent.
* Consequently, we created a final field named `evaluatorRegistry` that references
* the `BehaviorGuardEvaluatorRegistry` instance.
*
* <p>The first line of `fireEvent` retrieves the list of the behavior units that
* are defined in the SARL agent (and any internal behavior) for the given event.
*
* <p>The second part of the `fireEvent` function goes through the behavior units
* for evaluating there guards. The function `evaluateGuard` evaluates the guard
* of the behavior unit on the given event, and, if the guard is true,
* it fills the given list of handlers with a call to the behavior unit's code.
*
* <p>The third part of the `fireEvent` function invokes the behavior units' code
* that have a true guard.
*
* @filter(.* = '''|'''|.parseSuccessfully.*)
*/
fact "Firing SARL events" {
'''
val evaluatorRegistry = new BehaviorGuardEvaluatorRegistry
package def fireEvent(^event : Event) {
var evaluators = this.evaluatorRegistry.getBehaviorGuardEvaluators(^event)
var handlers : Collection<Runnable> = new ArrayList
for (evaluator : evaluators) {
evaluator.evaluateGuard(^event, handlers);
}
for (handler : handlers) {
handler.run();
}
}
'''.parseSuccessfully(
'''
package io.sarl.docs.tutorials.tinyMASSRE
import java.util.UUID
import java.util.Collection
import java.util.ArrayList
import io.sarl.lang.core.Event
interface BehaviorGuardEvaluator {
def evaluateGuard(e : Event, handlers : Collection<Runnable>)
}
class BehaviorGuardEvaluatorRegistry {
def getBehaviorGuardEvaluators(e : Event) : Collection<BehaviorGuardEvaluator> { null }
}
abstract class TMSarlAgent {
''',
// TEXT
'''
}
''')
}
/* For enabling the `BehaviorGuardEvaluatorRegistry` instance to retrieve the behavior units
* of the SARL agent (and any internal behavior), we must register the SARL agent
* as a provider of behavior units to the `BehaviorGuardEvaluatorRegistry` instance.
*
* <p>The easier way to proceed is to register the SARL agent when the tinyMAS agent is starting;
* and to unregister the SARL agent when the tinyMAS agent is stopping.
* These two life-cycle functions are supported by the `start` and `stop` functions in the tinyMAS
* platform.
*
* @filter(.* = '''|'''|.parseSuccessfully.*)
*/
fact "Registering the SARL agent as behavior unit provider" {
'''
def start {
super.start
this.evaluatorRegistry.register(getSarlAgent())
}
def stop {
this.evaluatorRegistry.unregister(getSarlAgent())
super.stop
}
'''.parseSuccessfully(
'''
package io.sarl.docs.tutorials.tinyMASSRE
import java.util.UUID
import java.util.Collection
import io.sarl.lang.core.Event
interface BehaviorGuardEvaluator {
def evaluateGuard(e : Event, handlers : Collection<Runnable>)
}
abstract class TinyMASAgent {
def start {}
def stop {}
}
class BehaviorGuardEvaluatorRegistry {
def register(e : Object) {}
def unregister(e : Object) {}
}
abstract class TMSarlAgent extends TinyMASAgent {
val evaluatorRegistry = new BehaviorGuardEvaluatorRegistry
def getSarlAgent : Object { null }
''',
// TEXT
'''
}
''')
}
/* For enabling the receiving of SARL events, we need to define a specific SARL event listener.
* The easier way is to implement the `EventListener` interface from the SARL API (see the code
* below).
*
* <p>The implementation of the `EventListener` interface implies to implement the
* `receiveEvent` function. This function is called by the SARL infrastructure each time
* an event must be treated by the agent, i.e. when the agent receives the event.
*
* <p>The function `receiveEvent` calls the already implemented function `fireEvent`.
* Nevertheless, the `receiveEvent` function must ensure that the given event has
* a source, i.e. the address of the sender of the event.
* If the event has no source, the value of the source is forced to the address of the current
* SARL agent.
*
* <p>In order to create the address of the current agent, we must know the
* address of the agent in the default interaction space, and consequently, the default context
* in which the agent exists.
* We defined the `defaultSpace` field and the corresponds getter function for storing the
* default space of the agent.
* For initializing this field, we redefine the constructor.
*
* @filter(.* = '''|'''|.parseSuccessfully.*)
*/
fact "Receiving SARL events" {
'''
class TMSarlAgent extends org.arakhne.tinyMAS.core.Agent implements io.sarl.lang.core.EventListener {
// [...]
val defaultSpace : WeakReference<TMDefaultSpace>
protected def getDefaultSpace : TMDefaultSpace {
this.defaultSpace.get
}
def receiveEvent(^event : Event) {
if (^event.source === null) {
^event.source = getDefaultSpace.getAddress(getSarlAgent.ID)
}
fireEvent(^event)
}
new (defaultSpace : TMDefaultSpace, sarlAgent : io.sarl.lang.core.Agent) {
this.defaultSpace = new WeakReference(defaultSpace)
this.sarlAgent = sarlAgent
}
}
'''.parseSuccessfully(
'''
package org.arakhne.tinyMAS.core
import java.lang.ref.WeakReference
import java.util.UUID
import io.sarl.lang.core.Event
import io.sarl.lang.core.Address
interface TMDefaultSpace {
def getAddress(id : UUID) : Address
}
abstract class Agent {
protected var sarlAgent : Object
abstract def getSarlAgent : io.sarl.lang.core.Agent
abstract def fireEvent(e : Event)
}
abstract
''',
// TEXT
'''
''')
}
/* According to the SARL specification, two events must be fired for supporting the
* agents' life-cycle. The first event corresponds to the initialization of the agent,
* the `Initialize` event. And, the second event corresponds to the destruction of the
* agent, the `Destroy` event.
*
* <p>The tinyMAS implementation of the SRE must fire these two events according
* to the tinyMAS agent life-cycle. In this platform, the starting of the agents
* is supported by the `start` function. And the destruction of the agents is supported
* by the `stop` function.
*
* <p>For firing the `Initialize` event, we need to create an instance of this event into
* the `start` function. But, from the SARL API documentation, the `Initialize` event
* must take the initialization parameters to pass to the agent at its start-up.
* For supporting these initialization parameters, we define the `parameters` field that is
* initialized in the agent type constructor.
* Then, the `start` function is updated for setting the parameters of the `Initialize` event;
* and for firing the event with a call to the `receiveEvent` function.
*
* <p>By symmetry, the `Destroy` event is initialize and fired in the `stop` function of the
* agent type.
*
* @filter(.* = '''|'''|.parseSuccessfully.*)
*/
fact "Initialize and Destroy events" {
'''
var parameters : Object[]
new (defaultSpace : TMDefaultSpace, sarlAgent : io.sarl.lang.core.Agent, parameters : Object[]) {
this.defaultSpace = new WeakReference(defaultSpace)
this.sarlAgent = sarlAgent
this.parameters = parameters
}
def start {
super.start
this.evaluatorRegistry.register(getSarlAgent())
var initializeEvent = new Initialize
if (this.parameters !== null) {
initializeEvent.parameters = this.parameters
this.parameters = null
}
receiveEvent(initializeEvent)
}
def stop {
receiveEvent(new Destroy)
this.evaluatorRegistry.unregister(getSarlAgent())
super.stop
}
'''.parseSuccessfully(
'''
package io.sarl.docs.tutorials.tinyMASSRE
import java.util.UUID
import java.lang.ref.WeakReference
import java.util.Collection
import io.sarl.lang.core.Event
import io.sarl.core.Initialize
import io.sarl.core.Destroy
interface BehaviorGuardEvaluator {
def evaluateGuard(e : Event, handlers : Collection<Runnable>)
}
abstract class TinyMASAgent {
def start {}
def stop {}
}
class BehaviorGuardEvaluatorRegistry {
def register(e : Object) {}
def unregister(e : Object) {}
}
interface TMDefaultSpace {}
abstract class TMSarlAgent extends TinyMASAgent {
val defaultSpace : WeakReference<TMDefaultSpace>
var sarlAgent : Object
val evaluatorRegistry = new BehaviorGuardEvaluatorRegistry
def getSarlAgent : Object { null }
def receiveEvent(e : Event) {}
''',
// TEXT
'''
}
''')
}
}
/* Spawning agents is a key feature of the execution platform.
* This feature is used for booting the initial agent, and by the agent built-in capacities
* for creating new agents.
*
* <p>In order to provide a reusable spawning function, we define the `Spawner` utility class
* that contains the static definition of the spawning functions of SARL agents on the tinyMAS
* platform.
*/
describe "Tool for spawning agents" {
/* The first utility function that we define is `createAgent`.
* It enables to create an instance of `TMSarlAgent` from a SARL agent type.
*
* <p>The parameters of the functions are the ones required for building an instance of a SARL agent:
*
* * `defaultSpace`: the instance of the default space in which the SARL agent will interact.
* * `agentType` : the type of SARL agent to create.
* * `parentID` : the identifier of the agent's parent, usually the identifier of the default context in the timeMAS SRE.
* * `agentID` : the identifier to give to the created agent, or <code>null</code> if the identifier must be randomly selected.
* * `params` : the initialization parameters to pass to the created SARL agent.
*
* <p>The function replies the created tinyMAS agent that is binded to the SARL agent.
*
* <p>The code of the SARL agent creation is based on the call to the SARL agent constructor, as
* defined in the SARL specification. By default, the SARL agent agents have a
* constructor with three parameters:
*
* * first parameter of type `BuiltinCapacitiesProvider`: a provider of built-in capacity. Here we pass <code>null</code> as argument to the constructor in order to ignore the default initialization of the built-in capacities. This initialization will be done manually in one of the following sections.
* * second parameter of type `UUID`: the identifier of the parent context of the created agent.
* * third parameter of type `UUID`: the identifier of the created agent.
*
* @filter(.* = '''|'''|.parseSuccessfully.*)
*/
fact "Creating a tinyMAS agent from a SARL agent" {
'''
static def createAgent(
defaultSpace : TMDefaultSpace,
agentType : Class<? extends io.sarl.lang.core.Agent>,
parentID : UUID,
agentID : UUID,
params : Object*)
: TMSarlAgent {
if (typeof(io.sarl.lang.core.Agent).isAssignableFrom(agentType)) {