LightJason - AgentSpeak(L++)
CASTVisitorAgent.java
Go to the documentation of this file.
1 /*
2  * @cond LICENSE
3  * ######################################################################################
4  * # LGPL License #
5  * # #
6  * # This file is part of the LightJason AgentSpeak(L++) #
7  * # Copyright (c) 2015-19, LightJason (info@lightjason.org) #
8  * # This program is free software: you can redistribute it and/or modify #
9  * # it under the terms of the GNU Lesser General Public License as #
10  * # published by the Free Software Foundation, either version 3 of the #
11  * # License, or (at your option) any later version. #
12  * # #
13  * # This program is distributed in the hope that it will be useful, #
14  * # but WITHOUT ANY WARRANTY; without even the implied warranty of #
15  * # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
16  * # GNU Lesser General Public License for more details. #
17  * # #
18  * # You should have received a copy of the GNU Lesser General Public License #
19  * # along with this program. If not, see http://www.gnu.org/licenses/ #
20  * ######################################################################################
21  * @endcond
22  */
23 
24 package org.lightjason.agentspeak.grammar;
25 
26 import com.google.common.collect.LinkedHashMultimap;
27 import com.google.common.collect.Multimap;
28 import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor;
29 import org.apache.commons.lang3.tuple.ImmutablePair;
30 import org.apache.commons.lang3.tuple.Pair;
88 
89 import javax.annotation.Nonnull;
90 import java.text.MessageFormat;
91 import java.util.Collection;
92 import java.util.Collections;
93 import java.util.HashSet;
94 import java.util.LinkedHashSet;
95 import java.util.LinkedList;
96 import java.util.List;
97 import java.util.Map;
98 import java.util.Objects;
99 import java.util.Set;
100 import java.util.logging.Logger;
101 import java.util.stream.Collectors;
102 
103 
110 @SuppressWarnings( {"all", "warnings", "unchecked", "unused", "cast"} )
111 public final class CASTVisitorAgent extends AbstractParseTreeVisitor<Object> implements IASTVisitorAgent
112 {
116  private static final Logger LOGGER = CCommon.logger( IASTVisitorAgent.class );
124  private final Set<ILiteral> m_initialbeliefs = new LinkedHashSet<>();
128  private final Set<IPlan> m_plans = new HashSet<>();
132  private final Multimap<IPath, IRule> m_rules = LinkedHashMultimap.create();
136  private final Map<IPath, IAction> m_actions;
137 
143  public CASTVisitorAgent( @Nonnull final Set<IAction> p_actions )
144  {
145  m_actions = p_actions.stream().collect( Collectors.toMap( i -> i.name(), i -> i ) );
146  LOGGER.info( MessageFormat.format( "create parser with actions & rules : {0} / {1}", m_actions.keySet(), m_rules.keySet() ) );
147  }
148 
149  // ---------------------------------------------------------------------------------------------------------------------------------------------------------
150 
151 
152  // --- agent rules -----------------------------------------------------------------------------------------------------------------------------------------
153 
154  @Override
155  public final Object visitAgent( final AgentParser.AgentContext p_context )
156  {
157  return this.visitChildren( p_context );
158  }
159 
160 
161 
162  @Override
163  public final Object visitInitial_beliefs( final AgentParser.Initial_beliefsContext p_context )
164  {
165  p_context.belief().stream().map( i -> (ILiteral) this.visitBelief( i ) ).forEach( m_initialbeliefs::add );
166  LOGGER.info( MessageFormat.format( "parsed initial beliefs: {0}", m_initialbeliefs ) );
167  return null;
168  }
169 
170 
171 
172  @Override
173  public final Object visitInitial_goal( final AgentParser.Initial_goalContext p_context )
174  {
175  m_initialgoal = CLiteral.from( (String) this.visitAtom( p_context.atom() ) );
176  LOGGER.info( MessageFormat.format( "parsed initial-goal: {0}", m_initialgoal ) );
177  return null;
178  }
179 
180  // ---------------------------------------------------------------------------------------------------------------------------------------------------------
181 
182 
183  // --- AgentSpeak(L) rules ---------------------------------------------------------------------------------------------------------------------------------
184 
185  @Override
186  public final Object visitBelief( final AgentParser.BeliefContext p_context )
187  {
188  return this.visitLiteral( p_context.literal() );
189  }
190 
191 
192 
193  @Override
194  public final Object visitPlans( final AgentParser.PlansContext p_context )
195  {
196  if ( Objects.isNull( p_context.plan() ) )
197  return null;
198 
199  p_context.plan().stream().forEach( i -> ( (List<IPlan>) this.visitPlan( i ) ).stream().forEach( j -> m_plans.add( j ) ) );
200  LOGGER.info( MessageFormat.format( "parsed plans: {0}", m_plans ) );
201  return null;
202  }
203 
204 
205 
206  @Override
207  public final Object visitLogicrules( final AgentParser.LogicrulesContext p_context )
208  {
209  // create placeholder objects first and run parsing again to build full-qualified rule objects
210  p_context.logicrule().stream()
211  .map( i -> (IRule) this.visitLogicrulePlaceHolder( i ) )
212  .forEach( i -> m_rules.put( i.identifier().fqnfunctor(), i ) );
213 
214  final Multimap<IPath, IRule> l_rules = LinkedHashMultimap.create();
215  p_context.logicrule().stream()
216  .flatMap( i -> ( (List<IRule>) this.visitLogicrule( i ) ).stream() )
217  .forEach( i -> l_rules.put( i.identifier().fqnfunctor(), i ) );
218 
219  // clear rule list and replace placeholder objects
220  m_rules.clear();
221  l_rules.values().stream()
222  .map( i -> i.replaceplaceholder( l_rules ) )
223  .forEach( i -> m_rules.put( i.identifier().fqnfunctor(), i ) );
224 
225  LOGGER.info( MessageFormat.format( "parsed rules: {0}", m_rules.values() ) );
226  return null;
227  }
228 
229  @Override
230  public final Object visitLogicrule( final AgentParser.LogicruleContext p_context )
231  {
232  final ILiteral l_literal = (ILiteral) this.visitLiteral( p_context.literal() );
233  return p_context.logicalruledefinition().stream()
234  .map( i -> new CRule( (ILiteral) l_literal.deepcopy(), (List<IExecution>) this.visitLogicalruledefinition( i ) ) )
235  .collect( Collectors.toList() );
236  }
237 
238  @Override
239  public final Object visitLogicalruledefinition( final AgentParser.LogicalruledefinitionContext p_context )
240  {
241  return this.visitBody( p_context.body() );
242  }
243 
244  @Override
245  public final Object visitPlan( final AgentParser.PlanContext p_context )
246  {
247  final Set<IAnnotation<?>> l_annotation = (Set<IAnnotation<?>>) this.visitAnnotations( p_context.annotations() );
248  final CTrigger l_trigger = new CTrigger(
249  (ITrigger.EType) this.visitPlan_trigger( p_context.plan_trigger() ),
250  (ILiteral) this.visitLiteral( p_context.literal() )
251  );
252 
253  return p_context.plandefinition()
254  .stream()
255  .map( i ->
256  {
257  final Pair<IExpression, List<IExecution>> l_content = (Pair<IExpression, List<IExecution>>) this.visitPlandefinition( i );
258  return new CPlan( l_trigger, l_content.getLeft(), l_content.getRight(), l_annotation );
259  } )
260  .collect( Collectors.toList() );
261  }
262 
263  @Override
264  public final Object visitPlandefinition( final AgentParser.PlandefinitionContext p_context )
265  {
266  return new ImmutablePair<IExpression, List<IExecution>>(
267  Objects.isNull( p_context.expression() )
269  : (IExpression) this.visitExpression( p_context.expression() ),
270  (List<IExecution>) this.visitBody( p_context.body() )
271  );
272  }
273 
274  @Override
275  public final Object visitAnnotations( final AgentParser.AnnotationsContext p_context )
276  {
277  if ( ( Objects.isNull( p_context ) ) || ( p_context.isEmpty() ) )
278  return Collections.emptySet();
279 
280 
281  final Set<IAnnotation<?>> l_annotation = new HashSet<>();
282 
283  if ( Objects.nonNull( p_context.annotation_atom() ) )
284  p_context.annotation_atom().stream().map( i -> (IAnnotation<?>) this.visitAnnotation_atom( i ) ).forEach( l_annotation::add );
285 
286  if ( Objects.nonNull( p_context.annotation_literal() ) )
287  p_context.annotation_literal().stream().map( i -> (IAnnotation<?>) this.visitAnnotation_literal( i ) ).forEach( l_annotation::add );
288 
289  return l_annotation.isEmpty() ? Collections.emptySet() : l_annotation;
290  }
291 
292  @Override
293  public final Object visitAnnotation_atom( final AgentParser.Annotation_atomContext p_context )
294  {
295  if ( Objects.nonNull( p_context.ATOMIC() ) )
297 
298  if ( Objects.nonNull( p_context.PARALLEL() ) )
300 
301  throw new CIllegalArgumentException( CCommon.languagestring( this, "atomannotation", p_context.getText() ) );
302  }
303 
304  @Override
305  public final Object visitAnnotation_literal( final AgentParser.Annotation_literalContext p_context )
306  {
307  return this.visitChildren( p_context );
308  }
309 
310  @Override
311  public Object visitAnnotation_value_literal( final AgentParser.Annotation_value_literalContext p_context )
312  {
313  if ( Objects.nonNull( p_context.number() ) )
314  return new CValueAnnotation<>(
316  (String) this.visitVariableatom( p_context.variableatom() ),
317  ( (Number) this.visitNumber( p_context.number() ) ).doubleValue()
318  );
319 
320  if ( Objects.nonNull( p_context.STRING() ) )
321  return new CValueAnnotation<>(
323  (String) this.visitVariableatom( p_context.variableatom() ),
324  stringvalue( p_context.STRING().getText() )
325  );
326 
327  throw new CIllegalArgumentException( CCommon.languagestring( this, "valueannotation", p_context.getText() ) );
328  }
329 
330  @Override
331  public final Object visitPlan_trigger( final AgentParser.Plan_triggerContext p_context )
332  {
333  return this.visitChildren( p_context );
334  }
335 
336  @Override
337  public final Object visitPlan_goal_trigger( final AgentParser.Plan_goal_triggerContext p_context )
338  {
339  if ( ITrigger.EType.ADDGOAL.sequence().equals( p_context.getText() ) )
340  return ITrigger.EType.ADDGOAL;
341 
342  if ( ITrigger.EType.DELETEGOAL.sequence().equals( p_context.getText() ) )
343  return ITrigger.EType.DELETEGOAL;
344 
345  throw new CIllegalArgumentException( CCommon.languagestring( this, "goaltrigger", p_context.getText() ) );
346  }
347 
348  @Override
349  public final Object visitPlan_belief_trigger( final AgentParser.Plan_belief_triggerContext p_context )
350  {
351  if ( ITrigger.EType.ADDBELIEF.sequence().equals( p_context.getText() ) )
352  return ITrigger.EType.ADDBELIEF;
353 
354  if ( ITrigger.EType.DELETEBELIEF.sequence().equals( p_context.getText() ) )
355  return ITrigger.EType.DELETEBELIEF;
356 
357  throw new CIllegalArgumentException( CCommon.languagestring( this, "belieftrigger", p_context.getText() ) );
358  }
359 
360  @Override
361  public final Object visitBody( final AgentParser.BodyContext p_context )
362  {
363  // filter null values of the body formular, because blank lines adds a null value, body-formula rule return an executable call everytime
364  return p_context.body_formula().stream()
365  .filter( i -> Objects.nonNull( i ) )
366  .map( i -> this.visitBody_formula( i ) )
367  .filter( i -> i instanceof IExecution )
368  // expression are encapsulate to get result
369  .map( i -> i instanceof IExpression ? new CRawAction<>( i ) : i )
370  .collect( Collectors.toList() );
371  }
372 
373  @Override
374  public final Object visitBody_formula( final AgentParser.Body_formulaContext p_context )
375  {
376  return this.visitChildren( p_context );
377  }
378 
379  @Override
380  public final Object visitRepair_formula( final AgentParser.Repair_formulaContext p_context )
381  {
382  // a non-existing repair formula can return any object-item, so convert it
383  // to executable structure, because the grammar rule must return an executable item
384  if ( Objects.isNull( p_context.repair_formula() ) )
385  return this.visitChildren( p_context );
386 
387 
388  // if there exists any repair element, build a sequential hierarchie of repair calls
389  if ( Objects.nonNull( p_context.executable_term() ) )
390  return new CRepair(
391  (IExecution) this.visitExecutable_term( p_context.executable_term() ),
392  (IExecution) this.visitRepair_formula( p_context.repair_formula() )
393  );
394 
395  if ( Objects.nonNull( p_context.test_action() ) )
396  return new CRepair(
397  (IExecution) this.visitTest_action( p_context.test_action() ),
398  (IExecution) this.visitRepair_formula( p_context.repair_formula() )
399  );
400 
401  if ( Objects.nonNull( p_context.achievement_goal_action() ) )
402  return new CRepair(
403  (IExecution) this.visitAchievement_goal_action( p_context.achievement_goal_action() ),
404  (IExecution) this.visitRepair_formula( p_context.repair_formula() )
405  );
406 
407  throw new CSyntaxErrorException( CCommon.languagestring( this, "repairelement", p_context.getText() ) );
408  }
409 
410  @Override
411  public final Object visitUnification( final AgentParser.UnificationContext p_context )
412  {
413  final Object l_constraint = this.visitUnification_constraint( p_context.unification_constraint() );
414 
415  if ( l_constraint instanceof IExpression )
416  return new CExpressionUnify(
417  p_context.AT() != null,
418  (ILiteral) this.visitLiteral( p_context.literal() ),
419  (IExpression) l_constraint
420  );
421 
422  if ( l_constraint instanceof IVariable<?> )
423  return new CVariableUnify(
424  p_context.AT() != null,
425  (ILiteral) this.visitLiteral( p_context.literal() ),
426  (IVariable<?>) l_constraint
427  );
428 
429  return new CDefaultUnify( p_context.AT() != null, (ILiteral) this.visitLiteral( p_context.literal() ) );
430  }
431 
432  @Override
433  public final Object visitUnification_constraint( final AgentParser.Unification_constraintContext p_context )
434  {
435  if ( Objects.isNull( p_context ) )
436  return null;
437 
438  if ( Objects.nonNull( p_context.expression() ) )
439  return this.visitExpression( p_context.expression() );
440 
441  if ( Objects.nonNull( p_context.variable() ) )
442  return this.visitVariable( p_context.variable() );
443 
444  return null;
445  }
446 
447  @Override
448  public final Object visitBlock_formula( final AgentParser.Block_formulaContext p_context )
449  {
450  if ( Objects.nonNull( p_context.body_formula() ) )
451  {
452  final LinkedList<IExecution> l_statement = new LinkedList<>();
453  l_statement.add( (IExecution) this.visitBody_formula( p_context.body_formula() ) );
454  return l_statement;
455  }
456 
457  return this.visitBody( p_context.body() );
458  }
459 
460  @Override
461  public final Object visitLambda( final AgentParser.LambdaContext p_context )
462  {
463  if ( Objects.nonNull( p_context.lambda_return() ) )
464  return new CLambdaExpression(
465  p_context.AT() != null,
466  (IExecution) this.visitLambda_initialization( p_context.lambda_initialization() ),
467  (IVariable<?>) this.visitVariable( p_context.variable() ),
468  (IVariable<?>) this.visitLambda_return( p_context.lambda_return() ),
469  (List<IExecution>) this.visitBlock_formula( p_context.block_formula() )
470  );
471 
472  return new CLambdaExpression(
473  p_context.AT() != null,
474  (IExecution) this.visitLambda_initialization( p_context.lambda_initialization() ),
475  (IVariable<?>) this.visitVariable( p_context.variable() ),
476  (List<IExecution>) this.visitBlock_formula( p_context.block_formula() )
477  );
478  }
479 
480  @Override
481  public final Object visitLambda_initialization( final AgentParser.Lambda_initializationContext p_context )
482  {
483  if ( Objects.nonNull( p_context.variable() ) )
484  return new CRawAction<>( this.visitVariable( p_context.variable() ) );
485 
486  if ( Objects.nonNull( p_context.literal() ) )
487  return new CProxyAction( m_actions, (ILiteral) this.visitLiteral( p_context.literal() ) );
488 
489  throw new CSyntaxErrorException( CCommon.languagestring( this, "lambdainitialization", p_context.getText() ) );
490  }
491 
492  @Override
493  public final Object visitLambda_return( final AgentParser.Lambda_returnContext p_context )
494  {
495  return this.visitVariable( p_context.variable() );
496  }
497 
498  @Override
499  public final Object visitExecutable_term( final AgentParser.Executable_termContext p_context )
500  {
501  if ( Objects.nonNull( p_context.STRING() ) )
502  return new CRawAction<>( stringvalue( p_context.STRING().getText() ) );
503  if ( Objects.nonNull( p_context.number() ) )
504  return new CRawAction<>( this.visitNumber( p_context.number() ) );
505  if ( Objects.nonNull( p_context.LOGICALVALUE() ) )
506  return new CRawAction<>( logicalvalue( p_context.LOGICALVALUE().getText() ) );
507 
508  if ( Objects.nonNull( p_context.executable_action() ) )
509  return this.visitExecutable_action( p_context.executable_action() );
510  if ( Objects.nonNull( p_context.executable_rule() ) )
511  return this.visitExecutable_rule( p_context.executable_rule() );
512 
513  if ( Objects.nonNull( p_context.expression() ) )
514  return this.visitExpression( p_context.expression() );
515  if ( Objects.nonNull( p_context.ternary_operation() ) )
516  return this.visitTernary_operation( p_context.ternary_operation() );
517 
518  throw new CIllegalArgumentException( CCommon.languagestring( this, "termunknown", p_context.getText() ) );
519  }
520 
521  @Override
522  public final Object visitAssignment_expression( final AgentParser.Assignment_expressionContext p_context )
523  {
524  return this.visitChildren( p_context );
525  }
526 
527  @Override
528  public final Object visitAssignment_expression_singlevariable( final AgentParser.Assignment_expression_singlevariableContext p_context )
529  {
530  return new CSingleAssignment<>(
531  (IVariable<?>) this.visitVariable( p_context.variable() ),
532  (IExecution) this.visitExecutable_term( p_context.executable_term() )
533  );
534  }
535 
536  @Override
537  public final Object visitAssignment_expression_multivariable( final AgentParser.Assignment_expression_multivariableContext p_context )
538  {
539  return new CMultiAssignment<>(
540  p_context.variablelist().variable().stream().map( i -> (IVariable<?>) this.visitVariable( i ) )
541  .collect( Collectors.toList() ),
542  (IExecution) this.visitExecutable_term( p_context.executable_term() )
543  );
544  }
545 
546  @Override
547  public final Object visitUnary_expression( final AgentParser.Unary_expressionContext p_context )
548  {
549  switch ( p_context.UNARYOPERATOR().getText() )
550  {
551  case "++":
552  return new CIncrement<>( (IVariable<Number>) this.visitVariable( p_context.variable() ) );
553 
554  case "--":
555  return new CDecrement<>( (IVariable<Number>) this.visitVariable( p_context.variable() ) );
556 
557  default:
558  throw new CIllegalArgumentException( CCommon.languagestring( this, "unaryoperator", p_context.getText() ) );
559  }
560  }
561 
562  @Override
563  public final Object visitBinary_expression( final AgentParser.Binary_expressionContext p_context )
564  {
565  final IVariable<Number> l_lhs = (IVariable<Number>) this.visitVariable( p_context.variable( 0 ) );
566  final ITerm l_rhs = p_context.variable().size() == 2
567  ? (IVariable<Number>) this.visitVariable( p_context.variable( 1 ) )
568  : CRawTerm.from( this.visitNumber( p_context.number() ) );
569 
570  return new COperatorAssign(
571  l_lhs, l_rhs, org.lightjason.agentspeak.language.execution.expressionbinary.EOperator.from( p_context.BINARYOPERATOR().getText() )
572  );
573  }
574 
575  @Override
576  public final Object visitAchievement_goal_action( final AgentParser.Achievement_goal_actionContext p_context )
577  {
578  if ( Objects.nonNull( p_context.literal() ) )
579  return new CAchievementGoalLiteral( (ILiteral) this.visitLiteral( p_context.literal() ), Objects.nonNull( p_context.DOUBLEEXCLAMATIONMARK() ) );
580 
581  if ( Objects.nonNull( p_context.variable_evaluate() ) )
582  return new CAchievementGoalVariable(
583  (IVariableEvaluate) this.visitVariable_evaluate( p_context.variable_evaluate() ),
584  Objects.nonNull( p_context.DOUBLEEXCLAMATIONMARK() )
585  );
586 
587  throw new CIllegalArgumentException( CCommon.languagestring( this, "achievmentgoal", p_context.getText() ) );
588  }
589 
590  @Override
591  public final Object visitTernary_operation( final AgentParser.Ternary_operationContext p_context )
592  {
593  return new CTernaryOperation(
594  (IExpression) this.visitExpression( p_context.expression() ),
595  (IExecution) this.visitTernary_operation_true( p_context.ternary_operation_true() ),
596  (IExecution) this.visitTernary_operation_false( p_context.ternary_operation_false() )
597  );
598  }
599 
600  @Override
601  public final Object visitTernary_operation_true( final AgentParser.Ternary_operation_trueContext p_context )
602  {
603  return this.visitExecutable_term( p_context.executable_term() );
604  }
605 
606  @Override
607  public final Object visitTernary_operation_false( final AgentParser.Ternary_operation_falseContext p_context )
608  {
609  return this.visitExecutable_term( p_context.executable_term() );
610  }
611 
612  @Override
613  public final Object visitTest_action( final AgentParser.Test_actionContext p_context )
614  {
615  // dollar sign is used to recognize a rule
616  return Objects.nonNull( p_context.DOLLAR() )
617  ? new CTestRule( CPath.from( (String) this.visitAtom( p_context.atom() ) ) )
618  : new CTestGoal( CPath.from( (String) this.visitAtom( p_context.atom() ) ) );
619  }
620 
621  @Override
622  public final Object visitBelief_action( final AgentParser.Belief_actionContext p_context )
623  {
624  if ( Objects.nonNull( p_context.PLUS() ) )
625  return new CBeliefAction( (ILiteral) this.visitLiteral( p_context.literal() ), CBeliefAction.EAction.ADD );
626 
627  if ( Objects.nonNull( p_context.MINUS() ) )
628  return new CBeliefAction( (ILiteral) this.visitLiteral( p_context.literal() ), CBeliefAction.EAction.DELETE );
629 
630  throw new CIllegalArgumentException( CCommon.languagestring( this, "beliefaction", p_context.getText() ) );
631  }
632 
633  @Override
634  public final Object visitDeconstruct_expression( final AgentParser.Deconstruct_expressionContext p_context )
635  {
636  return new CDeconstruct<>(
637  p_context.variablelist().variable().stream().map( i -> (IVariable<?>) this.visitVariable( i ) ).collect( Collectors.toList() ),
638  (ITerm) ( Objects.nonNull( p_context.literal() ) ? this.visitLiteral( p_context.literal() ) : this.visitVariable( p_context.variable() ) )
639  );
640  }
641 
642  // ---------------------------------------------------------------------------------------------------------------------------------------------------------
643 
644 
645  // --- simple datatypes ------------------------------------------------------------------------------------------------------------------------------------
646 
647  @Override
648  public final Object visitLiteral( final AgentParser.LiteralContext p_context )
649  {
650  return new CLiteral(
651  Objects.nonNull( p_context.AT() ),
652  Objects.nonNull( p_context.STRONGNEGATION() ),
653  CPath.from( this.visitAtom( p_context.atom() ).toString() ),
654  (Collection<ITerm>) this.visitTermlist( p_context.termlist() )
655  );
656  }
657 
658  @Override
659  public final Object visitTerm( final AgentParser.TermContext p_context )
660  {
661  if ( Objects.nonNull( p_context.STRING() ) )
662  return stringvalue( p_context.STRING().getText() );
663  if ( Objects.nonNull( p_context.number() ) )
664  return this.visitNumber( p_context.number() );
665  if ( Objects.nonNull( p_context.LOGICALVALUE() ) )
666  return logicalvalue( p_context.LOGICALVALUE().getText() );
667 
668  if ( Objects.nonNull( p_context.literal() ) )
669  return this.visitLiteral( p_context.literal() );
670  if ( Objects.nonNull( p_context.variable() ) )
671  return this.visitVariable( p_context.variable() );
672 
673  if ( Objects.nonNull( p_context.termlist() ) )
674  return this.visitTermlist( p_context.termlist() );
675  if ( Objects.nonNull( p_context.expression() ) )
676  return this.visitExpression( p_context.expression() );
677  if ( Objects.nonNull( p_context.ternary_operation() ) )
678  return this.visitTernary_operation( p_context.ternary_operation() );
679 
680  throw new CIllegalArgumentException( CCommon.languagestring( this, "termunknown", p_context.getText() ) );
681  }
682 
683  @Override
684  public final Object visitTermlist( final AgentParser.TermlistContext p_context )
685  {
686  if ( ( Objects.isNull( p_context ) ) || ( p_context.isEmpty() ) )
687  return Collections.<ITerm>emptyList();
688 
689  return p_context.term().stream()
690  .map( i -> this.visitTerm( i ) )
691  .filter( i -> Objects.nonNull( i ) )
692  .map( i -> i instanceof ITerm ? (ITerm) i : CRawTerm.from( i ) )
693  .collect( Collectors.toList() );
694  }
695 
696  @Override
697  public final Object visitVariablelist( final AgentParser.VariablelistContext p_context )
698  {
699  return this.visitChildren( p_context );
700  }
701 
702  // ---------------------------------------------------------------------------------------------------------------------------------------------------------
703 
704 
705  // --- raw rules -------------------------------------------------------------------------------------------------------------------------------------------
706 
707  @Override
708  public final Object visitNumber( final AgentParser.NumberContext p_context )
709  {
710  if ( Objects.nonNull( p_context.CONSTANTNUMBER() ) )
711  return numericonstant( p_context.CONSTANTNUMBER().getText() );
712 
713  final Number l_value = (Number) this.visitChildren( p_context );
714  return Objects.nonNull( p_context.MINUS() )
715  ? -1 * l_value.doubleValue()
716  : l_value.doubleValue();
717  }
718 
719  @Override
720  public final Object visitDigitsequence( final AgentParser.DigitsequenceContext p_context )
721  {
722  return Double.valueOf( p_context.getText() );
723  }
724 
725  @Override
726  public final Object visitAtom( final AgentParser.AtomContext p_context )
727  {
728  return p_context.getText();
729  }
730 
731  @Override
732  public final Object visitVariable( final AgentParser.VariableContext p_context )
733  {
734  return Objects.isNull( p_context.AT() )
735  ? new CVariable<>( (String) this.visitVariableatom( p_context.variableatom() ) )
736  : new CMutexVariable<>( (String) this.visitVariableatom( p_context.variableatom() ) );
737  }
738 
739  @Override
740  public final Object visitVariableatom( final AgentParser.VariableatomContext p_context )
741  {
742  return p_context.getText();
743  }
744 
745  @Override
746  public final Object visitExpression( final AgentParser.ExpressionContext p_context )
747  {
748  // bracket expression
749  if ( Objects.nonNull( p_context.expression_bracket() ) )
750  return this.visitExpression_bracket( p_context.expression_bracket() );
751 
752  // or-expression
754  EOperator.OR,
755  (IExpression) this.visitExpression_logical_and( p_context.expression_logical_and() ),
756  Objects.nonNull( p_context.expression() )
757  ? p_context.expression().stream().map( i -> (IExpression) this.visitExpression( i ) ).collect( Collectors.toList() )
758  : Collections.emptyList()
759  );
760  }
761 
762  @Override
763  public final Object visitExpression_bracket( final AgentParser.Expression_bracketContext p_context )
764  {
765  return this.visitExpression( p_context.expression() );
766  }
767 
768  @Override
769  public final Object visitExpression_logical_and( final AgentParser.Expression_logical_andContext p_context )
770  {
772  EOperator.AND,
773  (IExpression) this.visitExpression_logical_xor( p_context.expression_logical_xor() ),
774  Objects.nonNull( p_context.expression() )
775  ? p_context.expression().stream().map( i -> (IExpression) this.visitExpression( i ) ).collect( Collectors.toList() )
776  : Collections.emptyList()
777  );
778  }
779 
780  @Override
781  public final Object visitExpression_logical_xor( final AgentParser.Expression_logical_xorContext p_context )
782  {
783  if ( Objects.nonNull( p_context.expression_logical_element() ) )
785  EOperator.XOR,
786  (IExpression) this.visitExpression_logical_element( p_context.expression_logical_element() ),
787  Objects.nonNull( p_context.expression() )
788  ? p_context.expression().stream().map( i -> (IExpression) this.visitExpression( i ) ).collect( Collectors.toList() )
789  : Collections.emptyList()
790  );
791 
792  if ( Objects.nonNull( p_context.expression_logical_negation() ) )
793  return this.visitExpression_logical_negation( p_context.expression_logical_negation() );
794 
795  if ( Objects.nonNull( p_context.expression_numeric() ) )
796  return this.visitExpression_numeric( p_context.expression_numeric() );
797 
798  throw new CSyntaxErrorException( CCommon.languagestring( this, "logicallefthandside", p_context.getText() ) );
799  }
800 
801  @Override
802  public final Object visitExpression_logical_negation( final AgentParser.Expression_logical_negationContext p_context )
803  {
804  return new CUnary( EOperator.NEGATION, (IExpression) this.visitExpression( p_context.expression() ) );
805  }
806 
807  @Override
808  public final Object visitExpression_logical_element( final AgentParser.Expression_logical_elementContext p_context )
809  {
810  if ( Objects.nonNull( p_context.LOGICALVALUE() ) )
811  return new CAtom( logicalvalue( p_context.LOGICALVALUE().getText() ) );
812 
813  if ( Objects.nonNull( p_context.variable() ) )
814  return new CAtom( this.visitVariable( p_context.variable() ) );
815 
816  if ( Objects.nonNull( p_context.unification() ) )
817  return new CProxyReturnExpression<>( (IExecution) this.visitUnification( p_context.unification() ) );
818 
819  if ( Objects.nonNull( p_context.executable_action() ) )
820  return new CProxyReturnExpression<>( (IExecution) this.visitExecutable_action( p_context.executable_action() ) );
821 
822  if ( Objects.nonNull( p_context.executable_rule() ) )
823  return new CProxyReturnExpression<>( (IExecution) this.visitExecutable_rule( p_context.executable_rule() ) );
824 
825  throw new CSyntaxErrorException( CCommon.languagestring( this, "logicalelement", p_context.getText() ) );
826  }
827 
828  @Override
829  public final Object visitExpression_numeric( final AgentParser.Expression_numericContext p_context )
830  {
831  if ( Objects.isNull( p_context.expression_numeric() ) )
832  return this.visitExpression_numeric_relation( p_context.expression_numeric_relation() );
833 
834  if ( Objects.nonNull( p_context.EQUAL() ) )
835  return new CComparable(
837  (IExpression) this.visitExpression_numeric_relation( p_context.expression_numeric_relation() ),
838  (IExpression) this.visitExpression_numeric( p_context.expression_numeric() )
839  );
840 
841  if ( Objects.nonNull( p_context.NOTEQUAL() ) )
842  return new CComparable(
844  (IExpression) this.visitExpression_numeric_relation( p_context.expression_numeric_relation() ),
845  (IExpression) this.visitExpression_numeric( p_context.expression_numeric() )
846  );
847 
848  throw new CSyntaxErrorException( CCommon.languagestring( this, "compareoperator", p_context.getText() ) );
849  }
850 
851  @Override
852  public final Object visitExpression_numeric_relation( final AgentParser.Expression_numeric_relationContext p_context )
853  {
854  if ( Objects.isNull( p_context.expression_numeric() ) )
855  return this.visitExpression_numeric_additive( p_context.expression_numeric_additive() );
856 
857  if ( Objects.nonNull( p_context.GREATER() ) )
858  return new CRelational(
860  (IExpression) this.visitExpression_numeric_additive( p_context.expression_numeric_additive() ),
861  (IExpression) this.visitExpression_numeric( p_context.expression_numeric() )
862  );
863 
864  if ( Objects.nonNull( p_context.GREATEREQUAL() ) )
865  return new CRelational(
867  (IExpression) this.visitExpression_numeric_additive( p_context.expression_numeric_additive() ),
868  (IExpression) this.visitExpression_numeric( p_context.expression_numeric() )
869  );
870 
871  if ( Objects.nonNull( p_context.LESS() ) )
872  return new CRelational(
873  EOperator.LESS,
874  (IExpression) this.visitExpression_numeric_additive( p_context.expression_numeric_additive() ),
875  (IExpression) this.visitExpression_numeric( p_context.expression_numeric() )
876  );
877 
878  if ( Objects.nonNull( p_context.LESSEQUAL() ) )
879  return new CRelational(
881  (IExpression) this.visitExpression_numeric_additive( p_context.expression_numeric_additive() ),
882  (IExpression) this.visitExpression_numeric( p_context.expression_numeric() )
883  );
884 
885  throw new CSyntaxErrorException( CCommon.languagestring( this, "relationaloperator", p_context.getText() ) );
886  }
887 
888  @Override
889  public final Object visitExpression_numeric_additive( final AgentParser.Expression_numeric_additiveContext p_context )
890  {
891  if ( Objects.isNull( p_context.expression_numeric() ) )
892  return this.visitExpression_numeric_multiplicative( p_context.expression_numeric_multiplicative() );
893 
894  if ( Objects.nonNull( p_context.PLUS() ) )
895  return new CAdditive(
896  EOperator.PLUS,
897  (IExpression) this.visitExpression_numeric_multiplicative( p_context.expression_numeric_multiplicative() ),
898  (IExpression) this.visitExpression_numeric( p_context.expression_numeric() )
899  );
900 
901  if ( Objects.nonNull( p_context.MINUS() ) )
902  return new CAdditive(
904  (IExpression) this.visitExpression_numeric_multiplicative( p_context.expression_numeric_multiplicative() ),
905  (IExpression) this.visitExpression_numeric( p_context.expression_numeric() )
906  );
907 
908  throw new CSyntaxErrorException( CCommon.languagestring( this, "additiveoperator", p_context.getText() ) );
909  }
910 
911  @Override
912  public final Object visitExpression_numeric_multiplicative( final AgentParser.Expression_numeric_multiplicativeContext p_context )
913  {
914  if ( Objects.isNull( p_context.expression_numeric() ) )
915  return this.visitExpression_numeric_power( p_context.expression_numeric_power() );
916 
917  if ( Objects.nonNull( p_context.MULTIPLY() ) )
918  return new CMultiplicative(
920  (IExpression) this.visitExpression_numeric_power( p_context.expression_numeric_power() ),
921  (IExpression) this.visitExpression_numeric( p_context.expression_numeric() )
922  );
923 
924  if ( Objects.nonNull( p_context.SLASH() ) )
925  return new CMultiplicative(
927  (IExpression) this.visitExpression_numeric_power( p_context.expression_numeric_power() ),
928  (IExpression) this.visitExpression_numeric( p_context.expression_numeric() )
929  );
930 
931  if ( Objects.nonNull( p_context.MODULO() ) )
932  return new CMultiplicative(
934  (IExpression) this.visitExpression_numeric_power( p_context.expression_numeric_power() ),
935  (IExpression) this.visitExpression_numeric( p_context.expression_numeric() )
936  );
937 
938  throw new CSyntaxErrorException( CCommon.languagestring( this, "multiplicativeoperator", p_context.getText() ) );
939  }
940 
941  @Override
942  public final Object visitExpression_numeric_power( final AgentParser.Expression_numeric_powerContext p_context )
943  {
944  if ( Objects.isNull( p_context.expression_numeric() ) )
945  return this.visitExpression_numeric_element( p_context.expression_numeric_element() );
946 
947  return new CPower(
949  (IExpression) this.visitExpression_numeric_element( p_context.expression_numeric_element() ),
950  (IExpression) this.visitExpression_numeric( p_context.expression_numeric() )
951  );
952  }
953 
954  @Override
955  public final Object visitExpression_numeric_element( final AgentParser.Expression_numeric_elementContext p_context )
956  {
957  if ( Objects.nonNull( p_context.number() ) )
958  return new CAtom( this.visitNumber( p_context.number() ) );
959 
960  if ( Objects.nonNull( p_context.variable() ) )
961  return new CAtom( this.visitVariable( p_context.variable() ) );
962 
963  if ( Objects.nonNull( p_context.executable_action() ) )
964  return new CProxyReturnExpression<>( (IExecution) this.visitExecutable_action( p_context.executable_action() ) );
965 
966  if ( Objects.nonNull( p_context.executable_rule() ) )
967  return new CProxyReturnExpression<>( (IExecution) this.visitExecutable_rule( p_context.executable_rule() ) );
968 
969  throw new CSyntaxErrorException( CCommon.languagestring( this, "numericelement", p_context.getText() ) );
970  }
971 
972  @Override
973  public final Object visitExecutable_action( final AgentParser.Executable_actionContext p_context )
974  {
975  return new CProxyAction( m_actions, (ILiteral) this.visitLiteral( p_context.literal() ) );
976  }
977 
978  @Override
979  public final Object visitExecutable_rule( final AgentParser.Executable_ruleContext p_context )
980  {
981  if ( Objects.nonNull( p_context.literal() ) )
982  return new CAchievementRuleLiteral( (ILiteral) this.visitLiteral( p_context.literal() ) );
983 
984  if ( Objects.nonNull( p_context.variable_evaluate() ) )
985  return new CAchievementRuleVariable( (IVariableEvaluate) this.visitVariable_evaluate( p_context.variable_evaluate() ) );
986 
987  throw new CSyntaxErrorException( CCommon.languagestring( this, "executablerule", p_context.getText() ) );
988  }
989 
990  @Override
991  public final Object visitVariable_evaluate( final AgentParser.Variable_evaluateContext p_context )
992  {
993  return new CVariableEvaluate(
994  (IVariable<?>) this.visitVariable( p_context.variable() ),
995  (List<ITerm>) this.visitTermlist( p_context.termlist() )
996  );
997  }
998 
999  // ---------------------------------------------------------------------------------------------------------------------------------------------------------
1000 
1001 
1002  // --- helper ----------------------------------------------------------------------------------------------------------------------------------------------
1003 
1010  protected Object visitLogicrulePlaceHolder( final AgentParser.LogicruleContext p_context )
1011  {
1012  return new CRulePlaceholder( (ILiteral) this.visitLiteral( p_context.literal() ) );
1013  }
1014 
1021  private static Number numericonstant( @Nonnull final String p_value )
1022  {
1023  final Double l_constant = org.lightjason.agentspeak.grammar.CCommon.NUMERICCONSTANT.get( p_value );
1024  if ( Objects.nonNull( l_constant ) )
1025  return l_constant;
1026 
1027  throw new CSyntaxErrorException( CCommon.languagestring( CASTVisitorAgent.class, "constantunknown", p_value ) );
1028  }
1029 
1036  private static boolean logicalvalue( @Nonnull final String p_value )
1037  {
1038  return ( !p_value.isEmpty() ) && ( ( "true".equals( p_value ) ) || ( "success".equals( p_value ) ) );
1039  }
1040 
1047  private static String stringvalue( @Nonnull final String p_value )
1048  {
1049  return p_value.length() < 3 ? "" : p_value.substring( 1, p_value.length() - 1 );
1050  }
1051 
1052  // ---------------------------------------------------------------------------------------------------------------------------------------------------------
1053 
1054 
1055  // --- getter structure ------------------------------------------------------------------------------------------------------------------------------------
1056 
1057  @Nonnull
1058  @Override
1059  public final Set<ILiteral> initialbeliefs()
1060  {
1061  return m_initialbeliefs;
1062  }
1063 
1064  @Nonnull
1065  @Override
1066  public final Set<IPlan> plans()
1067  {
1068  return m_plans;
1069  }
1070 
1071  @Nonnull
1072  @Override
1073  public final Set<IRule> rules()
1074  {
1075  return new HashSet<>( m_rules.values() );
1076  }
1077 
1078  @Override
1079  public final ILiteral initialgoal()
1080  {
1081  return m_initialgoal;
1082  }
1083 
1084  // ---------------------------------------------------------------------------------------------------------------------------------------------------------
1085 
1086 }
final Object visitInitial_beliefs(final AgentParser.Initial_beliefsContext p_context)
static Number numericonstant( @Nonnull final String p_value)
returns the value of a numeric constant
final Object visitRepair_formula(final AgentParser.Repair_formulaContext p_context)
final Object visitPlandefinition(final AgentParser.PlandefinitionContext p_context)
final Object visitPlan(final AgentParser.PlanContext p_context)
final Object visitBelief_action(final AgentParser.Belief_actionContext p_context)
final Object visitAssignment_expression_singlevariable(final AgentParser.Assignment_expression_singlevariableContext p_context)
final Object visitPlan_trigger(final AgentParser.Plan_triggerContext p_context)
final Object visitLambda_initialization(final AgentParser.Lambda_initializationContext p_context)
final Object visitLogicrules(final AgentParser.LogicrulesContext p_context)
final Object visitPlans(final AgentParser.PlansContext p_context)
IExpression EMPTY
empty expression, is always true
final Object visitPlan_goal_trigger(final AgentParser.Plan_goal_triggerContext p_context)
placeholder rule to define correct rule referencing
final Set< IPlan > plans()
get a multimap with event-plan matching
final Object visitDeconstruct_expression(final AgentParser.Deconstruct_expressionContext p_context)
final Object visitLambda(final AgentParser.LambdaContext p_context)
final Object visitTermlist(final AgentParser.TermlistContext p_context)
final Object visitTernary_operation_false(final AgentParser.Ternary_operation_falseContext p_context)
final Object visitAssignment_expression_multivariable(final AgentParser.Assignment_expression_multivariableContext p_context)
final Object visitExecutable_rule(final AgentParser.Executable_ruleContext p_context)
final Object visitExecutable_term(final AgentParser.Executable_termContext p_context)
final Object visitExpression_numeric_element(final AgentParser.Expression_numeric_elementContext p_context)
final Object visitAssignment_expression(final AgentParser.Assignment_expressionContext p_context)
final Object visitExpression_bracket(final AgentParser.Expression_bracketContext p_context)
static IPath from( @Nonnull final String p_string)
factor method to build path
Definition: CPath.java:166
final Object visitVariable(final AgentParser.VariableContext p_context)
static< T > String languagestring(final T p_source, final String p_label, final Object... p_parameter)
returns the language depend string on any object
class to create a path structure
Definition: CPath.java:53
encapsulate class for any non-executable data type e.g.
Definition: CRawAction.java:47
final Object visitExpression(final AgentParser.ExpressionContext p_context)
final Object visitAtom(final AgentParser.AtomContext p_context)
final Object visitTest_action(final AgentParser.Test_actionContext p_context)
final Object visitTernary_operation(final AgentParser.Ternary_operationContext p_context)
final Object visitExpression_logical_and(final AgentParser.Expression_logical_andContext p_context)
final Map< IPath, IAction > m_actions
map with action definition
final Object visitExpression_numeric_additive(final AgentParser.Expression_numeric_additiveContext p_context)
final Object visitVariableatom(final AgentParser.VariableatomContext p_context)
final Object visitBinary_expression(final AgentParser.Binary_expressionContext p_context)
visitor interface of the abstract-syntax-tree (AST) for an agent
final Object visitUnification(final AgentParser.UnificationContext p_context)
final Set< IRule > rules()
returns the rules / principles
default abstract-syntax-tree (AST) visitor for agent scripts
external action interface
Definition: IAction.java:38
final Object visitUnary_expression(final AgentParser.Unary_expressionContext p_context)
final Object visitVariablelist(final AgentParser.VariablelistContext p_context)
final Object visitExpression_numeric(final AgentParser.Expression_numericContext p_context)
final Object visitTernary_operation_true(final AgentParser.Ternary_operation_trueContext p_context)
static Logger logger(final Class<?> p_class)
returns a logger instance
final Object visitExpression_logical_xor(final AgentParser.Expression_logical_xorContext p_context)
final Object visitLambda_return(final AgentParser.Lambda_returnContext p_context)
static String stringvalue( @Nonnull final String p_value)
create a string value without quotes
final Object visitAchievement_goal_action(final AgentParser.Achievement_goal_actionContext p_context)
final ILiteral initialgoal()
returns the initial goal
static EOperator from( @Nonnull final String p_value)
returns operator from string
final Object visitAgent(final AgentParser.AgentContext p_context)
final Object visitTerm(final AgentParser.TermContext p_context)
final Object visitNumber(final AgentParser.NumberContext p_context)
final Object visitExecutable_action(final AgentParser.Executable_actionContext p_context)
defines an execution element with a repair call
Definition: CRepair.java:42
Object visitLogicrulePlaceHolder(final AgentParser.LogicruleContext p_context)
create a rule placeholder object
final Object visitBody(final AgentParser.BodyContext p_context)
default generic literal class for agent beliefs a literal consists of a functor, an optional list of ...
Definition: CLiteral.java:64
CASTVisitorAgent( @Nonnull final Set< IAction > p_actions)
ctor
final Object visitExpression_logical_element(final AgentParser.Expression_logical_elementContext p_context)
static IExpression createLogicalBinaryExpression( @Nonnull final EOperator p_operator, @Nonnull final IExpression p_lefthandside, @Nonnull final Collection< IExpression > p_righthandside)
creates a logical expression concationation with single operator
static boolean logicalvalue( @Nonnull final String p_value)
converts a string token to the type
T deepcopy( @Nullable final IPath... p_prefix)
clones the object (shallow-copy)
static< N > CRawTerm< N > from(final N p_value)
factory for a raw term
Definition: CRawTerm.java:104
final Object visitAnnotation_literal(final AgentParser.Annotation_literalContext p_context)
final Object visitExpression_numeric_relation(final AgentParser.Expression_numeric_relationContext p_context)
static ILiteral from( @Nonnull final String p_functor, @Nullable final ITerm... p_values)
factory
Definition: CLiteral.java:161
final Object visitExpression_numeric_multiplicative(final AgentParser.Expression_numeric_multiplicativeContext p_context)
Object visitAnnotation_value_literal(final AgentParser.Annotation_value_literalContext p_context)
final Object visitBody_formula(final AgentParser.Body_formulaContext p_context)
static final Map< String, Double > NUMERICCONSTANT
numeric constant values - infinity is defined manually
final Object visitUnification_constraint(final AgentParser.Unification_constraintContext p_context)
final Object visitBelief(final AgentParser.BeliefContext p_context)
final Set< ILiteral > initialbeliefs()
returns initial beliefs
final Object visitExpression_numeric_power(final AgentParser.Expression_numeric_powerContext p_context)
final Object visitAnnotation_atom(final AgentParser.Annotation_atomContext p_context)
final Object visitInitial_goal(final AgentParser.Initial_goalContext p_context)
final Object visitVariable_evaluate(final AgentParser.Variable_evaluateContext p_context)
final Object visitLiteral(final AgentParser.LiteralContext p_context)
final Object visitExpression_logical_negation(final AgentParser.Expression_logical_negationContext p_context)
final Object visitAnnotations(final AgentParser.AnnotationsContext p_context)
final Object visitPlan_belief_trigger(final AgentParser.Plan_belief_triggerContext p_context)
final Object visitLogicrule(final AgentParser.LogicruleContext p_context)
term structure for simple datatypes
Definition: CRawTerm.java:45
final Object visitDigitsequence(final AgentParser.DigitsequenceContext p_context)
final Object visitLogicalruledefinition(final AgentParser.LogicalruledefinitionContext p_context)
final Object visitBlock_formula(final AgentParser.Block_formulaContext p_context)