-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLocus.rb
362 lines (334 loc) · 11.3 KB
/
Locus.rb
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
#!/usr/bin/env ruby
#-----------------------------------------------
# Locus
#-----------------------------------------------
# Mau Magnaguagno
# Ramon Pereira
# Anibal Solon
#-----------------------------------------------
# - AgentSpeak-like environment specification language for Jason
# - Source-to-source compiler
#-----------------------------------------------
# Feb 2015
# - Created
# - Structured as a module
# - Recursive descent parser
# - Metaprogramming to easily extend the conversion
# Mar 2015
# - Tests
#-----------------------------------------------
module Locus
extend self
VERSION = '0.0.1'
MAP_AGENTS_STRUCTURE = ' private Map<String, String> agents = new HashMap<String, String>();'
MAP_AGENTS =
' /* Agent map with class */
// First argument must be the mas2j filename in order to map agents with their classes
// environment: TestEnv("ag-names.mas2j")
try {
jason.mas2j.parser.mas2j parser = new jason.mas2j.parser.mas2j(new FileInputStream(args[0]));
MAS2JProject project;
project = parser.mas();
for (AgentParameters ap : project.getAgents()) {
String agName = ap.name;
for (int cAg = 0; cAg < ap.getNbInstances(); cAg++) {
String numberedAg = agName;
if (ap.getNbInstances() > 1) {
numberedAg += (cAg + 1);
}
agents.put(numberedAg, ap.name);
}
}
System.out.println(agents);
} catch (jason.mas2j.parser.ParseException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}'
#-----------------------------------------------
# Read
#-----------------------------------------------
def read(filename)
group = ''
count_paren = 0
(str = File.read(filename)).gsub!(/\/\/[^\n]*|\/\*.*?\*\/|\n/m,'')
str.scan(/[.()]|[^.()]+/) {|c|
case c
when '.'
if count_paren.zero?
# Only triggering events can be matched, several blocks are optional
# [prefix] event[(terms)] [: context] [<- body]
if group =~ /^\s*([-+~]+)?(\w+)(?:\((.*?)\))?(?:\s*:\s*(.+?))?(?:\s*<-\s*(\S.*))?\s*$/
if respond_to?(event = $2)
prefix = $1
terms = $3
context = $4
body = $5
send(event, prefix, terms&.split(/\s*,\s*/), context, body&.split(/\s*;\s*/))
group.clear
next
else raise "No match for #{event}"
end
else raise "Malformed expression in #{group}"
end
end
when '('
count_paren += 1
when ')'
raise "Missing open parentheses in #{group}" if (count_paren -= 1) < 0
end
group << c
}
raise "Missing close parentheses in #{group}" if count_paren != 0
raise "Malformed expression in #{group}" unless group.empty?
end
#-----------------------------------------------
# Parser
#-----------------------------------------------
def parser(command, string, close_command = true, indent = '', terms = nil)
# Recursive commands are matched
case command
# Percept
when /^([+-])percept\(([^)]+)\)(?:\s*:\s*(.+))?$/
prefix = $1
condition = $3
target, functor, *arguments = $2.split(/\s*,\s*/)
string << indent
if condition
case condition
when 'true'
condition = nil
when 'false'
return
else
string << 'if('
parser(condition, string, false)
string << ") {\n " << indent
end
end
if functor
string << (prefix == '+' ? 'addPercept(' : 'removePercept(')
string << "\"#{target}\", " if target != 'all'
literal = "Literal.parseLiteral(\"#{functor}"
ground = argument_parser(literal, arguments, terms)
literal << '")'
if ground
index = @literals.index(literal)
if index
string << "literal#{index}"
else
string << "literal#{@literals.size}"
@literals << literal
end
else
string << literal
end
else
string << 'clearPercepts('
string << "\"#{target}\"" if target != 'all'
end
string << ')'
string << ";\n" if close_command
string << indent << "}\n" if condition
# State
when /^(-?\+?)state\((.+)\)$/
prefix = $1
predicate, *arguments = $2.split(/\s*,\s*/)
positive = predicate.delete_prefix!('~') ? false : true
string << indent
key = "\"#{predicate}"
argument_parser(key, arguments, terms)
key << '"'
case prefix
when ''
string << "#{positive ? '' : '!'}this.state.get(#{key})"
when '+', '-+'
string << "this.state.put(#{key}, #{positive})"
when '-'
# TODO do not ignore if positive or negative
# If it removes bob, only (bob,true) can be removed
# If it removes ~bob, only (bob,false) can be removed
string << "this.state.remove(#{key})"
end
string << ";\n" if close_command
# AgentClass
when /^agentClass\((.+)\)$/
string << "this.agents.get(agName).equals(\"#{$1}\")"
string << ";\n" if close_command
@map_agents = true
# AgentName
when /^agentName\((.+)\)$/
string << "agName.equals(\"#{$1}\")"
string << ";\n" if close_command
# Consider Java inline
else
puts "Warning: the following command is considered Java code:\n #{command}"
string << indent << command
string << ";\n" if close_command
end
end
#-----------------------------------------------
# Argument parser
#-----------------------------------------------
def argument_parser(str, arguments, terms)
ground = true
unless arguments.empty?
str << '('
arguments.each_with_index {|arg, index|
if arg.match?(/^[A-Z]/)
str << "\" + action.getTerm(#{terms.index(arg)}).toString() + \""
ground = false
else
str << arg
end
str << ',' if index < arguments.size - 1
}
str << ')'
end
ground
end
#-----------------------------------------------
# Make string
#-----------------------------------------------
def make_string(dataset)
string = ''
dataset.each {|command| parser(command, string, true, ' ')}
string
end
#-----------------------------------------------
# Import string
#-----------------------------------------------
def import_string
string = ''
@user_imports.each {|i| string << "import #{i};\n"}
string
end
#-----------------------------------------------
# Constants string
#-----------------------------------------------
def constants_string
string = ''
@literals.each_with_index {|lit,i| string << " static final Literal literal#{i} = #{lit};\n"}
string
end
#-----------------------------------------------
# Actions string
#-----------------------------------------------
def actions_string
string = ' '
@actions.each {|name, terms, context, body|
string << "if(action.getFunctor().equals(\"#{name}\")) {\n"
if context
string << ' if('
parser(context, string, false)
string << ") {\n"
body.each {|command| parser(command, string, true, ' ', terms)}
string << " }\n"
else
body.each {|command| parser(command, string, true, ' ', terms)}
end
string << ' } else '
}
string << "{\n logger.info(\"executing: \" + action + \", but not implemented!\");\n }" unless @actions.empty?
string
end
#-----------------------------------------------
# AgentSpeak events
#-----------------------------------------------
def include(prefix, terms, context, body)
puts "Warning: prefix #{prefix} is ignored for include command" if prefix
puts "Warning: context #{context} is ignored for include command" if context
@user_imports.concat(terms) if terms
puts "Warning: context #{context} is ignored for include command" if context
puts "Warning: body #{body} is ignored for include command" if body
end
def init(prefix, terms, context, body)
puts "Warning: prefix #{prefix} is ignored for init command" if prefix
puts "Warning: terms #{terms} is ignored for init" if terms
puts "Warning: context #{context} is ignored for init" if context
@init.concat(body) if body
end
def stop(prefix, terms, context, body)
puts "Warning: prefix #{prefix} is ignored for stop command" if prefix
puts "Warning: terms #{terms} is ignored for stop" if terms
puts "Warning: context #{context} is ignored for stop" if context
@stop.concat(body) if body
end
def beforeActions(prefix, terms, context, body)
puts "Warning: prefix #{prefix} is ignored for beforeActions command" if prefix
puts "Warning: terms #{terms} is ignored for beforeActions" if terms
puts "Warning: context #{context} is ignored for beforeActions" if context
@before.concat(body) if body
end
def afterActions(prefix, terms, context, body)
puts "Warning: prefix #{prefix} is ignored for afterActions command" if prefix
puts "Warning: terms #{terms} is ignored for afterActions" if terms
puts "Warning: context #{context} is ignored for afterActions" if context
@after.concat(body) if body
end
def action(prefix, terms, context, body)
puts "Warning: prefix #{prefix} must be '+' for action command" if prefix != '+'
if body and not body.empty? then @actions << [terms.shift, terms, context, body]
else puts "Warning: action #{terms[0]} have no body"
end
end
#-----------------------------------------------
# To Java
#-----------------------------------------------
def to_java(filename)
@environment_name = File.basename(filename,'.esl')
@user_imports = []
@literals = []
@init = []
@stop = []
@before = []
@after = []
@actions = []
@map_agents = false
# Read file and match non-recursive commands
read(filename)
# Template fields are updated with data
template = File.read('locus_env.java')
template.gsub!('<ENVIRONMENT_NAME>', @environment_name)
template.sub!('<TIME>', Time.now.to_s)
template.sub!('<IMPORTS>', import_string)
template.sub!('<INIT>', make_string(@init))
template.sub!('<STOP>', make_string(@stop))
template.sub!('<BEFORE_ACTIONS>', make_string(@before))
template.sub!('<ACTIONS>', actions_string)
template.sub!('<AFTER_ACTIONS>', make_string(@after))
template.sub!('<CONSTANTS>', constants_string)
# Add map agent code if required
if @map_agents
template.sub!('<MAP_AGENTS_STRUCTURE>', MAP_AGENTS_STRUCTURE)
template.sub!('<MAP_AGENTS>', MAP_AGENTS)
else
template.slice!('<MAP_AGENTS_STRUCTURE>')
template.slice!('<MAP_AGENTS>')
end
template
end
end
#-----------------------------------------------
# Main
#-----------------------------------------------
if $0 == __FILE__
begin
if ARGV.size == 1 and ARGV[0] != '-h'
filename = ARGV[0]
if File.exist?(filename)
# Convert
javaenv = Locus.to_java(filename)
# Save to file
File.write(filename = filename.sub(/esl$/,'java'), javaenv)
puts "Saved to file #{filename}"
else abort("File not found: #{filename}")
end
else
puts 'Use Locus filename.esl'
end
rescue
puts $!, $@
exit(2)
end
end