Class: RedShift::Component

Inherits:
Object show all
Includes:
CShadow
Defined in:
lib/redshift/target/c/world-gen.rb,
lib/redshift/meta.rb,
lib/redshift/port.rb,
lib/redshift/syntax.rb,
lib/redshift/component.rb,
lib/redshift/target/c/component-gen.rb

Overview

move this to component-gen.rb

Defined Under Namespace

Classes: ActionPhase, ConnectPhase, ContState, ContVarAttribute, ContVarDescriptor, DynamicEventValue, EventPhase, EventPhaseItem, ExprAttribute, ExprEventValue, ExprWrapper, FlowAttribute, FlowWrapper, FunctionWrapper, GuardAttribute, GuardPhase, GuardWrapper, Literal, PhaseItem, Port, PostPhase, QMatch, ResetPhase, SyncPhase, SyncPhaseItem

Constant Summary collapse

VAR_TYPES =
[:constant_variables, :continuous_variables, :link_variables,
:input_variables]
INPUT_NONE =
0
INPUT_CONT_VAR =
1
INPUT_CONST =
2
INPUT_INP_VAR =
3

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(world) ⇒ Component

Returns a new instance of Component.



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
# File 'lib/redshift/component.rb', line 277

def initialize(world)
  if $REDSHIFT_DEBUG
    unless caller[1] =~ /redshift\/world.*`create'\z/ or
           caller[0] =~ /`initialize'\z/
      raise ArgumentError, "Components can be created only using " +
            "the create method of a world.", caller
    end
  end

  __set__world world
  self.var_count = self.class.var_count
  
  restore {
    @start_state = Enter
    self.cont_state = self.class.cont_state_class.new
    
    do_defaults
    yield self if block_given?
    do_setup
    
    if state
      raise RuntimeError, "Can't assign to state.\n" +
        "Occurred in initialization of component of class #{self.class}."
    end ## is this a useful restriction?
    
    self.state = @start_state
  }
end

Class Attribute Details

.subclassesObject (readonly)

Component is abstract, and not included in subclasses. This returns nil when called on subs.



18
19
20
# File 'lib/redshift/meta.rb', line 18

def subclasses
  @subclasses
end

Instance Attribute Details

#nameObject

Returns the value of attribute name.



133
134
135
# File 'lib/redshift/component.rb', line 133

def name
  @name
end

#start_stateObject (readonly)

Returns the value of attribute start_state.



132
133
134
# File 'lib/redshift/component.rb', line 132

def start_state
  @start_state
end

Class Method Details

._offset_tableObject



573
574
575
# File 'lib/redshift/target/c/component-gen.rb', line 573

def _offset_table
  {}
end

.add_var_to_offset_table(var_name) ⇒ Object



607
608
609
610
611
612
613
614
615
# File 'lib/redshift/target/c/component-gen.rb', line 607

def add_var_to_offset_table var_name
  ssn = shadow_struct_name
  lit = shadow_library.literal_symbol(var_name,
    shadow_library_source_file)
  offset_table_method.body %{\
    rb_hash_aset(table, #{lit},
      INT2FIX((char *)&(((struct #{ssn} *)0)->#{var_name}) - (char *)0));
  } ## can we just use offsetof() ?
end

.all_transitions(s) ⇒ Object



103
104
105
106
107
108
109
# File 'lib/redshift/meta.rb', line 103

def all_transitions(s)
  if self < Component
    own_transitions(s) + superclass.all_transitions(s)
  else
    own_transitions(s)
  end
end

.attach(states, features) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
# File 'lib/redshift/meta.rb', line 63

def attach states, features
  if features.class != Array
    features = [features]
  end

  case states
    when Array;  attach_flows states, features
    when Hash;   attach_transitions states, features
    else         raise SyntaxError, "Bad state list: #{states.inspect}"
  end
end

.attach_constant_variables(kind, var_names) ⇒ Object

kind is :strict, :piecewise, or :permissive



156
157
158
# File 'lib/redshift/meta.rb', line 156

def attach_constant_variables(kind, var_names)
  attach_variables(constant_variables, kind, var_names)
end

.attach_continuous_variables(kind, var_names) ⇒ Object

kind is :strict, :piecewise, or :permissive



151
152
153
# File 'lib/redshift/meta.rb', line 151

def attach_continuous_variables(kind, var_names)
  attach_variables(continuous_variables, kind, var_names)
end

.attach_flows(states, new_flows) ⇒ Object



75
76
77
78
79
80
81
82
# File 'lib/redshift/meta.rb', line 75

def attach_flows states, new_flows
  states.each do |state|
    fl = flows(state)
    for f in new_flows
      fl[f.var] = f
    end
  end
end

.attach_input(kind, var_names) ⇒ Object



160
161
162
163
164
# File 'lib/redshift/meta.rb', line 160

def attach_input(kind, var_names)
  var_names.each do |var_name|
    input_variables[var_name.to_sym] = kind
  end
end


44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/redshift/meta.rb', line 44

def attach_link vars, strictness
  unless not strictness or strictness == :strict
    raise ArgumentError, "Strictness must be false or :strict"
  end
  unless vars.is_a? Hash
    raise SyntaxError, "Arguments to link must be of form :var => class, " +
      "where class can be either a Class or a string denoting class name"
  end
  vars.each do |var_name, var_type|
    link_variables[var_name.to_sym] = [var_type, strictness]
  end
end

.attach_state(name) ⇒ Object



57
58
59
60
61
# File 'lib/redshift/meta.rb', line 57

def attach_state name
  state = State.new(name, self)
  const_set(name, state)
  states[name] = state
end

.attach_transitions(state_pairs, new_transitions) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
# File 'lib/redshift/meta.rb', line 84

def attach_transitions state_pairs, new_transitions
  new_transitions.delete_if {|t| t.guard && t.guard.any?{|g| g==false}}
  state_pairs.each do |src, dst|
    a = own_transitions(src)
    new_transitions.each do |t|
      name = t.name
      a.delete_if {|u,d| u.name == name}
      a << [t, dst]
    end
  end
end

.attach_variables(dest, kind, var_names, var_type = nil) ⇒ Object



139
140
141
142
143
144
145
146
147
148
# File 'lib/redshift/meta.rb', line 139

def attach_variables(dest, kind, var_names, var_type = nil)
  if var_names.last.kind_of? Hash
    h = var_names.pop
    var_names.concat h.keys.sort_by {|n|n.to_s}
    defaults h
  end
  var_names.each do |var_name|
    dest[var_name.to_sym] = var_type ? [var_type, kind] : kind
  end
end

.cached_outgoing_transition_data(s) ⇒ Object

Raises:

  • (Library::CommitError)


1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
# File 'lib/redshift/target/c/component-gen.rb', line 1170

def self.cached_outgoing_transition_data s
  raise Library::CommitError if $REDSHIFT_DEBUG and not committed?
  @cached_outgoing_transition_data ||= {}
  @cached_outgoing_transition_data[s] ||= begin
    ary = outgoing_transition_data(s)
    if queue_sleepable_states[s]
      ary[-1] |= 0x02 ## yuck!
    end
    ary.freeze
    ary
  end
end

.check_variablesObject



658
659
660
661
662
663
664
665
# File 'lib/redshift/target/c/component-gen.rb', line 658

def check_variables
  bad = constant_variables.keys & continuous_variables.keys
  unless bad.empty?
    raise ConstnessError,
      "In class #{self}, the following variables are " +
      "each defined as both constant and continuous: #{bad.join(", ")}."
  end
end

.constant(*var_names) ⇒ Object Also known as: piecewise_constant



156
157
158
# File 'lib/redshift/syntax.rb', line 156

def constant(*var_names)
  attach_constant_variables(:piecewise, var_names)
end

.cont_state_classObject



373
374
375
# File 'lib/redshift/target/c/component-gen.rb', line 373

def cont_state_class
  @cont_state_class ||= ContState.make_subclass_for(self)
end

.continuous(*var_names) ⇒ Object Also known as: piecewise_continuous



143
144
145
# File 'lib/redshift/syntax.rb', line 143

def continuous(*var_names)
  attach_continuous_variables(:piecewise, var_names)
end

.defaults(h = nil, &block) ⇒ Object Also known as: default

Register, for the current component class, the given block to be called at the beginning of initialization of an instance. The block is called with the world as self. Any number of blocks can be registered.



81
82
83
84
# File 'lib/redshift/syntax.rb', line 81

def defaults(h = nil, &block)
  (@defaults_procs ||= []) << block if block
  (@defaults_map ||= {}).update make_init_value_map(h) if h
end

.define_connects(connects) ⇒ Object



779
780
781
782
783
784
785
786
787
788
789
790
791
792
# File 'lib/redshift/target/c/component-gen.rb', line 779

def define_connects connects
  connects.each do |input_var, connect_spec|
    unless input_variables.key? input_var
      raise "Not an input variable: #{input_var}; in class #{self}"
    end
    
    case connect_spec
    when Proc, NilClass
      # nothing to do in this case
    when Array
      raise "unimplemented" ##
    end
  end
end

.define_constant(kind, var_names) ⇒ Object



468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'lib/redshift/target/c/component-gen.rb', line 468

def define_constant(kind, var_names)
  var_names.collect do |var_name|
    var_name = var_name.intern if var_name.is_a? String
    add_var_to_offset_table(var_name)
    
    (r,w), = shadow_attr_accessor var_name => "double #{var_name}"
    w.body "if (shadow->world) shadow->world->d_tick++"

    if kind == :strict
      exc = shadow_library.declare_class StrictnessError
      msg = "Cannot reset strictly constant #{var_name} in #{self}."
      w.body %{
        if (!NIL_P(shadow->state))
          rs_raise(#{exc}, shadow->self, #{msg.inspect});
      }
    end
  end
end

.define_constant_variablesObject



673
674
675
676
677
# File 'lib/redshift/target/c/component-gen.rb', line 673

def define_constant_variables
  constant_variables.own.keys.sort_by{|k|k.to_s}.each do |var_name|
    define_constant(constant_variables[var_name], [var_name])
  end
end

.define_continuous(kind, var_names) ⇒ Object



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
# File 'lib/redshift/target/c/component-gen.rb', line 387

def define_continuous(kind, var_names)
  var_names.collect do |var_name|
    var_name = var_name.intern if var_name.is_a? String
    
    cont_state_class.add_var var_name, kind do
      ssn = cont_state_class.shadow_struct_name
      exc = shadow_library.declare_class(AlgebraicAssignmentError)
      msg = "Cannot set #{var_name}; it is defined algebraically."

      class_eval %{
        define_c_method :#{var_name} do
          declare :cont_state => "#{ssn} *cont_state"
          declare :var        => "ContVar *var"
          body %{
            cont_state = (#{ssn} *)shadow->cont_state;
            var = &cont_state->#{var_name};
            if (var->algebraic &&
                (var->strict ? !var->d_tick :
                 var->d_tick != shadow->world->d_tick)) {
              (*var->flow)((ComponentShadow *)shadow);
            }
            else {
              if (shadow->world)
                var->d_tick = shadow->world->d_tick;
            }
          }
          # The d_tick assign above is because we now know that the
          # current-ness of the value has been relied upon (possibly to
          # go to strict sleep), and so the ck_strict flag must be set
          # later, so strictness will get checked at the end of any
          # transitions (but only if someone has relied on it).
          
          returns "rb_float_new(cont_state->#{var_name}.value[0])"
        end
      }
      
      ## the .strict ? check can be done statically (but cost is
      ## recompile if strict decl changes).

      if kind == :strict
        exc2 = shadow_library.declare_class StrictnessError
        msg2 = "Cannot reset strictly continuous #{var_name} in #{self}."
        class_eval %{
          define_c_method :#{var_name}= do
            arguments :value
            declare :cont_state => "#{ssn} *cont_state"
            body %{
              cont_state = (#{ssn} *)shadow->cont_state;
              cont_state->#{var_name}.value[0] = NUM2DBL(value);
              if (shadow->world)
                shadow->world->d_tick++;
              if (cont_state->#{var_name}.algebraic)
                rs_raise(#{exc}, shadow->self, #{msg.inspect});
              if (!NIL_P(shadow->state))
                rs_raise(#{exc2}, shadow->self, #{msg2.inspect});
            }
            returns "value"
          end
        }

      else
        class_eval %{
          define_c_method :#{var_name}= do
            arguments :value
            declare :cont_state => "#{ssn} *cont_state"
            body %{
              cont_state = (#{ssn} *)shadow->cont_state;
              cont_state->#{var_name}.value[0] = NUM2DBL(value);
              if (shadow->world) 
                shadow->world->d_tick++;
              if (cont_state->#{var_name}.algebraic)
                rs_raise(#{exc}, shadow->self, #{msg.inspect});
            }
            returns "value"
          end
        }
      end
    end
  end
end

.define_continuous_variablesObject



667
668
669
670
671
# File 'lib/redshift/target/c/component-gen.rb', line 667

def define_continuous_variables
  continuous_variables.own.keys.sort_by{|k|k.to_s}.each do |var_name|
    define_continuous(continuous_variables[var_name], [var_name])
  end
end

.define_event_phase(phase) ⇒ Object



893
894
895
896
897
898
899
900
901
902
903
# File 'lib/redshift/target/c/component-gen.rb', line 893

def define_event_phase phase
  phase.each do |item|
    case item.value
    when ExprEventValue
      reset = define_reset(item.value)
      after_commit do
        item.value = reset.wrapper
      end
    end
  end
end

.define_eventsObject



565
566
567
568
569
570
571
# File 'lib/redshift/target/c/component-gen.rb', line 565

def define_events
  exported_events.own.each do |event, index|
    define_method event do
      event_values.at(index) ## is it worth doing this in C?
    end                      ## or at least use eval instead of closure
  end
end

.define_flow(flow, state, var) ⇒ Object



692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
# File 'lib/redshift/target/c/component-gen.rb', line 692

def define_flow flow, state, var
  cont_var = cont_state_class.vars[var]
  unless cont_var
    attach_continuous_variables(:permissive, [var])
    cont_var = define_continuous(:permissive, [var])[0]
  end

  flow_hash[ [state, cont_var] ] ||= begin
    after_commit do
      ## a pity to use after_commit, when "just_before_commit" would be ok
      ## use the defer mechanism from teja2hsif
      if not flow.strict and cont_var.strict?
        raise StrictnessError,
          "Strict variable '#{cont_var.name}' in #{self} " +
          "redefined with non-strict flow.", []
      end
    end

    @flow_wrapper_hash ||= {}
    @flow_wrapper_hash[ [flow.var, flow.formula] ] ||=
      flow.become_generatable(self, state)
  end
end

.define_flows(state) ⇒ Object



685
686
687
688
689
690
# File 'lib/redshift/target/c/component-gen.rb', line 685

def define_flows(state)
  own_flows = flows(state).own
  own_flows.keys.sort_by{|sym|sym.to_s}.each do |var|
    define_flow own_flows[var], state, var
  end
end

.define_guard(expr) ⇒ Object



716
717
718
719
720
# File 'lib/redshift/target/c/component-gen.rb', line 716

def define_guard(expr)
  @guard_hash ||= {} ## could be a superhash?
  @guard_hash[expr] ||=
    CexprGuard.new(expr).become_generatable(self)
end

.define_guards(guards) ⇒ Object



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
# File 'lib/redshift/target/c/component-gen.rb', line 728

def define_guards(guards)
  guards.map! do |g|
    case g
    when Symbol
      # already saw this guard, as in: transition [S, T] => U
      g
    
    when QMatch
      g
    
    when Proc
      meth = Component.make_guard_method_name
      class_eval do
        define_method(meth, &g)
      end
      ## Currently, methods defined with define_method are a little
      ## slower to invoke in ruby.
      meth
    
    when String
      define_guard(g)
    
    when CexprGuard
      # already defined (shared guards)
      g

    else
      raise "Can't define guard for #{g.class} : #{g.inspect}"
    end
  end
  after_commit do
    guards.map! do |g|
      case g
      when CexprGuard
        g.wrapper
      else
        g
      end
    end
  end
end

.define_input(kind, var_names) ⇒ Object



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
# File 'lib/redshift/target/c/component-gen.rb', line 513

def define_input(kind, var_names)
  Component.input_target_struct
  
  var_names.collect do |var_name|
    var_name = var_name.intern if var_name.is_a? String
    
    src_comp    = src_comp(var_name)
    src_type    = src_type(var_name)
    src_offset  = src_offset(var_name)
    
    add_var_to_offset_table(src_comp)

    ## readers only?
    shadow_attr_accessor src_comp   => [Component]
    shadow_attr_accessor src_type   => "short #{src_type}"
    shadow_attr_accessor src_offset => "short #{src_offset}"
    
    define_c_method(var_name) do
      declare :result => "double result"
      returns "rb_float_new(result)"
      
      body %{
        result = rs_eval_input_var(shadow, &shadow->#{src_comp});
      }
    end
  end
end

.define_input_variablesObject



679
680
681
682
683
# File 'lib/redshift/target/c/component-gen.rb', line 679

def define_input_variables
  input_variables.own.keys.sort_by{|k|k.to_s}.each do |var_name|
    define_input(input_variables[var_name], [var_name])
  end
end


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
# File 'lib/redshift/target/c/component-gen.rb', line 617

def define_links
  ssn = shadow_struct_name
  
  link_variables.own.keys.sort_by{|k|k.to_s}.each do |var_name|
    var_type, strictness = link_variables[var_name]

    unless var_type.is_a? Class
      var_type = var_type.to_s.split(/::/).inject(self) do |p, n|
        p.const_get(n)
      end
      link_variables[var_name] = [var_type, strictness]
    end

    unless var_type <= Component
      raise TypeError,
      "Linked type must be a subclass of Component: #{var_name}"
    end

    (r,w), = shadow_attr_accessor(var_name => [var_type])
    w.body "if (shadow->world) shadow->world->d_tick++"

    if strictness == :strict
      exc = shadow_library.declare_class StrictnessError
      msg = "Cannot reset strict link #{var_name} in #{self}."
      w.body %{
        if (!NIL_P(shadow->state))
          rs_raise(#{exc}, shadow->self, #{msg.inspect});
      }
    end
    
    add_var_to_offset_table(var_name)
  end
  
  link_variables.keys.sort_by{|k|k.to_s}.each do |var_name|
    var_type, strictness = link_variables[var_name]
  
    shadow_library_source_file.include(
      var_type.shadow_library_include_file)
  end
end

.define_reset(expr, type = "double") ⇒ Object



794
795
796
797
798
# File 'lib/redshift/target/c/component-gen.rb', line 794

def define_reset(expr, type = "double")
  @expr_hash ||= {} ## could be a superhash?
  @expr_hash[expr] ||=
    ResetExpr.new(expr, type).become_generatable(self)
end

.define_reset_constant(var, expr, phase) ⇒ Object



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
# File 'lib/redshift/target/c/component-gen.rb', line 845

def define_reset_constant var, expr, phase
  if constant_variables[var] == :strict
    raise StrictnessError,
      "Cannot reset strictly constant #{var} in #{self}.", []
  end
  
  case expr
  when String
    reset = define_reset(expr)

    after_commit do
      phase << [offset_of_var(var), reset.wrapper, var]
    end

  when Numeric
    after_commit do
      phase << [offset_of_var(var), expr.to_f, var]
    end

  else
    after_commit do
      phase << [offset_of_var(var), expr, var]
    end
  end
end

.define_reset_continuous(cont_var, expr, phase) ⇒ Object



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
# File 'lib/redshift/target/c/component-gen.rb', line 818

def define_reset_continuous cont_var, expr, phase
  if cont_var.strict?
    raise StrictnessError,
      "Cannot reset strictly continuous '#{cont_var.name}' in #{self}.",
     []
  end

  case expr
  when String
    reset = define_reset(expr)

    after_commit do
      phase[cont_var.index] = reset.wrapper
    end
  
  when Numeric
    after_commit do
      phase[cont_var.index] = expr.to_f
    end

  else
    after_commit do
      phase[cont_var.index] = expr
    end
  end
end


871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
# File 'lib/redshift/target/c/component-gen.rb', line 871

def define_reset_link var, expr, phase
  type, strictness = link_variables[var]
  if strictness == :strict
    raise StrictnessError,
      "Cannot reset strict link #{var} in #{self}.", []
  end
  
  case expr
  when String
    reset = define_reset(expr, "ComponentShadow *")

    after_commit do
      phase << [offset_of_var(var), reset.wrapper, var, type]
    end

  when Proc, NilClass
    after_commit do
      phase << [offset_of_var(var), expr, var, type]
    end
  end
end

.define_resets(phase) ⇒ Object



800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
# File 'lib/redshift/target/c/component-gen.rb', line 800

def define_resets(phase)
  h = phase.value_map
  h.keys.sort_by{|k|k.to_s}.each do |var|
    expr = h[var]
    
    case
    when (cont_var = cont_state_class.vars[var])
      define_reset_continuous(cont_var, expr, (phase[0]||=[]))
    when constant_variables[var]
      define_reset_constant(var, expr, (phase[1]||=[]))
    when link_variables[var]
      define_reset_link(var, expr, (phase[2]||=[]))
    else
      raise "No such variable, #{var}"
    end
  end
end

.define_rs_eval_input_varObject



1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
# File 'lib/redshift/target/c/component-gen.rb', line 1325

def self.define_rs_eval_input_var
  shadow_library_source_file.define(:rs_eval_input_var).instance_eval do
    scope :extern
    arguments "ComponentShadow *shadow, char *psrc_comp"
    return_type "double"
    returns "result"

    exc_uncn = declare_class(UnconnectedInputError)
    exc_circ = declare_class(CircularDefinitionError)

    msg_uncn = "Input %s is not connected."
    msg_circ = "Circularity in input variable %s."

    body %{\
      double            result;
      struct target    *tgt     = (struct target *)(psrc_comp);
      ComponentShadow  *sh;
      int               depth   = 0;

    loop:
      if (!tgt->psh || tgt->type == INPUT_NONE) {
        size_t offset = psrc_comp - (char *)shadow;
        VALUE str = rb_funcall(shadow->self,
          #{declare_symbol :get_varname_by_offset}, 1, INT2FIX(offset));
        char *var_name = StringValuePtr(str);
        rs_raise(#{exc_uncn}, shadow->self, #{msg_uncn.inspect}, var_name);
      }

      sh = (ComponentShadow *)tgt->psh;

      switch(tgt->type) {
      case INPUT_CONT_VAR: {
        ContVar *var = (ContVar *)&FIRST_CONT_VAR(sh);
        var += tgt->offset;

        if (var->algebraic) {
          if (var->rk_level < sh->world->rk_level ||
             (sh->world->rk_level == 0 &&
              (var->strict ? !var->d_tick :
               var->d_tick != sh->world->d_tick) //## !world ?
              ))
            (*var->flow)(sh);
        }
        else {
          if (sh->world)
            var->d_tick = sh->world->d_tick;
        }

        result = var->value[sh->world->rk_level];
        break;
      }

      case INPUT_CONST:
        result = *(double *)(tgt->psh + tgt->offset);
        break;

      case INPUT_INP_VAR:
        tgt = (struct target *)(tgt->psh + tgt->offset);
        if (depth++ > sh->world->input_depth_limit) {
          size_t offset = psrc_comp - (char *)shadow;
          VALUE str = rb_funcall(shadow->self,
            #{declare_symbol :get_varname_by_offset}, 1, INT2FIX(offset));
          char *var_name = StringValuePtr(str);
          rs_raise(#{exc_circ}, shadow->self,
            #{msg_circ.inspect}, var_name);
        }
        goto loop;

      default:
        assert(0);
      }
    }
  end
end

.define_syncs(syncs) ⇒ Object



770
771
772
773
774
775
776
777
# File 'lib/redshift/target/c/component-gen.rb', line 770

def define_syncs syncs
  after_commit do
    syncs.each do |sync_phase_item|
      sync_phase_item.link_offset =
        offset_of_var(sync_phase_item.link_name)
    end
  end
end

.define_transitions(state) ⇒ Object



905
906
907
908
909
910
911
912
913
914
915
# File 'lib/redshift/target/c/component-gen.rb', line 905

def define_transitions(state)
  # transitions don't usually have names, so the following (insertion
  # order) is better than sorting by name.
  own_transitions(state).each do |trans, dst|
    define_guards(trans.guard) if trans.guard
    define_syncs(trans.sync) if trans.sync
    define_resets(trans.reset) if trans.reset
    define_event_phase(trans.event) if trans.event
    define_connects(trans.connect) if trans.connect
  end
end

.do_assignment_map(instance, h) ⇒ Object



338
339
340
341
342
343
# File 'lib/redshift/component.rb', line 338

def self.do_assignment_map instance, h
  ## could be done in c code
  h.each do |writer, val|
    instance.send writer, val
  end
end

.do_defaults(instance) ⇒ Object



345
346
347
348
349
350
351
352
353
# File 'lib/redshift/component.rb', line 345

def self.do_defaults instance
  superclass.do_defaults instance if superclass.respond_to? :do_defaults
  do_assignment_map instance, @defaults_map if @defaults_map
  if @defaults_procs
    @defaults_procs.each do |pr|
      instance.instance_eval(&pr)
    end
  end
end

.do_setup(instance) ⇒ Object



355
356
357
358
359
360
361
362
363
364
365
# File 'lib/redshift/component.rb', line 355

def self.do_setup instance
  ## should be possible to turn off superclass's setup so that 
  ## it can be overridden. 'nosupersetup'? explicit 'super'?
  superclass.do_setup instance if superclass.respond_to? :do_setup
  do_assignment_map instance, @setup_map if @setup_map
  if @setup_procs
    @setup_procs.each do |pr|
      instance.instance_eval(&pr)
    end
  end
end

.export(*events) ⇒ Object

Declare events to be exported (optional). Returns array of corresponding event indexes which can be used in code generation.



26
27
28
29
30
# File 'lib/redshift/meta.rb', line 26

def export(*events)
  events.map do |event|
    exported_events[event.to_sym] ||= exported_events.size
  end
end

.fetch_wrapper(name) ⇒ Object



107
108
109
110
# File 'lib/redshift/target/c/component-gen.rb', line 107

def Component.fetch_wrapper name
  raise unless self == Component
  @fn_wrapper_by_name && @fn_wrapper_by_name[name]
end

.find_var_superhash(var_name) ⇒ Object



166
167
168
169
# File 'lib/redshift/meta.rb', line 166

def find_var_superhash var_name
  [continuous_variables, constant_variables,
   link_variables, input_variables].find {|sh| sh[var_name]}
end

.flow(*states, &block) ⇒ Object

Define flows in this component class. Flows are attached to all of the states listed. The block contains method calls such as:

alg "var = expression"
diff "var' = expression"


485
486
487
488
489
490
491
# File 'lib/redshift/syntax.rb', line 485

def Component.flow(*states, &block)
  raise "no flows specified. Put { on same line!" unless block  
  states = states.map {|s| must_be_state(s)}
  states = [Enter] if states == []
  
  attach states, FlowSyntax.parse(block)
end

.flow_hashObject

The flow hash contains flows contributed (not inherited) by this class. The flow table is the cumulative hash (by state) of arrays (by var) of flows.



348
349
350
# File 'lib/redshift/target/c/component-gen.rb', line 348

def flow_hash
  @flow_hash ||= {}
end

.flow_tableObject



352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/redshift/target/c/component-gen.rb', line 352

def flow_table
  unless @flow_table
    assert committed?
    ft = {}
    if defined? superclass.flow_table
      for k, v in superclass.flow_table
        ft[k] = v.dup
      end
    end
    for (state, var), flow in flow_hash
      (ft[state] ||= [])[var.index] = flow.wrapper
    end
    @flow_table = ft
  end
  @flow_table
end

.generate_wrappersObject



556
557
558
559
560
561
562
563
# File 'lib/redshift/target/c/component-gen.rb', line 556

def generate_wrappers
  hs = [flow_hash, @guard_hash, @expr_hash]
  hs.compact.each do |h|
    h.values.sort_by{|f| f.fname}.each do |flow|
      flow.generate ### should rename Flow class to Function or such
    end
  end
end

.inherited(sub) ⇒ Object



20
21
22
# File 'lib/redshift/meta.rb', line 20

def inherited(sub)
  Component.subclasses << sub
end

.input(*var_names) ⇒ Object



179
180
181
# File 'lib/redshift/syntax.rb', line 179

def input(*var_names)
  attach_input :piecewise, var_names
end

.input_target_structObject



499
500
501
502
503
504
505
506
507
508
509
510
511
# File 'lib/redshift/target/c/component-gen.rb', line 499

def input_target_struct
  unless @input_target_struct
    sf = shadow_library_source_file
    st = @input_target_struct = sf.declare_extern_struct(:target)
    st.declare :psh    => "char    *psh"
    st.declare :type   => "short   type"
    st.declare :offset => "short   offset"
    ## will this always have the same layout as the struct members
    ## in ComponentShadow?
    
    define_rs_eval_input_var
  end
end

.inv_offset_tableObject



581
582
583
# File 'lib/redshift/target/c/component-gen.rb', line 581

def inv_offset_table
  @inv_offset_table ||= offset_table.invert
end

link :x => MyComponent, :y => :FwdRefComponent



166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/redshift/syntax.rb', line 166

def link(*vars)
  h = {}
  vars.each do |var|
    case var
    when Hash
      h.update var
    else
      h[var] = Component
    end
  end
  attach_link h, false
end

.literal(val) ⇒ Object



188
189
190
# File 'lib/redshift/component.rb', line 188

def Component.literal val
  Literal.new val
end

.make_guard_method_nameObject



722
723
724
725
726
# File 'lib/redshift/target/c/component-gen.rb', line 722

def make_guard_method_name
  @guard_ids ||= 0
  @guard_ids += 1
  "__guard_method_impl__#{@guard_ids}".intern
end

.make_init_value_map(h) ⇒ Object



67
68
69
70
71
72
73
74
75
# File 'lib/redshift/syntax.rb', line 67

def make_init_value_map(h)
  h.inject({}) do |hh, (var, val)|
    if val.kind_of? Proc or val.kind_of? String
      raise TypeError,
        "value for '#{var}' must be literal, like #{var} => 1.23"
    end
    hh.update "#{var}=" => val
  end
end

.must_be_state(s) ⇒ Object



565
566
567
568
569
570
571
572
573
574
575
# File 'lib/redshift/syntax.rb', line 565

def Component.must_be_state s
  return s if s.kind_of?(State)
  state = const_get(s.to_s)
rescue NameError
  raise TypeError, "Not a state: #{s.inspect}"
else
  unless state.kind_of?(State)
    raise TypeError, "Not a state: #{s.inspect}"
  end
  state
end

.next_comp_idObject



200
201
202
# File 'lib/redshift/component.rb', line 200

def Component.next_comp_id
  @next_comp_id += 1
end

.offset_of_var(var_name) ⇒ Object

Note: for constant and link vars. Offset is in bytes.



586
587
588
589
# File 'lib/redshift/target/c/component-gen.rb', line 586

def offset_of_var var_name
  offset_table[var_name.to_sym] or
    raise "#{var_name.inspect} is not a valid constant or link in #{self}"
end

.offset_tableObject



577
578
579
# File 'lib/redshift/target/c/component-gen.rb', line 577

def offset_table
  @offset_table ||= _offset_table
end

.offset_table_methodObject



597
598
599
600
601
602
603
604
605
# File 'lib/redshift/target/c/component-gen.rb', line 597

def offset_table_method
  @offset_table_method ||= define_c_class_method :_offset_table do
      declare :table  => "VALUE table"
      returns "table"
      body %{
        table = rb_call_super(0, 0);
      }
    end
end

.outgoing_transition_data(s) ⇒ Object



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
# File 'lib/redshift/meta.rb', line 111

def outgoing_transition_data s
  raise unless committed?
  
  ary = []
  all_strict = true
  seen = {}
  all_transitions(s).each do |t, d|
    next if seen[t.name] # overridden in subclass
    seen[t.name] = true

    t_strict = !t.sync || t.sync.empty?
    guard_list = t.guard
    guard_list and guard_list.each do |g|
      t_strict &&= g.respond_to?(:strict) && g.strict
    end
    all_strict &&= t_strict

    ary << [t, d, t.guard, t_strict]
  end

  result = []
  ary.reverse_each do |list| # since step_discrete reads them in reverse
    result.concat list
  end
  result << (all_strict ? 1 : 0) # other bits are used elsewhere
  result
end

.own_transitions(s) ⇒ Object

returns list of transitions from state s in evaluation order (just the ones defined in this class)



98
99
100
101
# File 'lib/redshift/meta.rb', line 98

def own_transitions(s)
  @own_transitions ||= {}
  @own_transitions[s] ||= []
end

.permissively_constant(*var_names) ⇒ Object



148
149
150
# File 'lib/redshift/syntax.rb', line 148

def permissively_constant(*var_names)
  attach_constant_variables(:permissive, var_names)
end

.permissively_continuous(*var_names) ⇒ Object



135
136
137
# File 'lib/redshift/syntax.rb', line 135

def permissively_continuous(*var_names)
  attach_continuous_variables(:permissive, var_names)
end

.precommitObject



541
542
543
544
545
546
547
548
549
550
551
552
553
554
# File 'lib/redshift/target/c/component-gen.rb', line 541

def precommit
  define_events
  define_links
  define_continuous_variables
  define_constant_variables
  define_input_variables

  states.values.sort_by{|s|s.to_s}.each do |state|
    define_flows(state)
    define_transitions(state)
  end

  check_variables
end

.queue(*var_names) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/redshift/meta.rb', line 32

def queue(*var_names)
  var_names.each do |var_name|
    next if queues[var_name]
    queues[var_name] = true
    class_eval %{
      def #{var_name}
        @#{var_name} ||= Queue.new(self)
      end
    }
  end
end

.queue_sleepable_statesObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/redshift/target/c/component-gen.rb', line 18

def self.queue_sleepable_states
  @queue_sleepable_states ||= begin
    raise Library::CommitError unless committed?
    h = {}
    states.values.each do |st|
      trs = all_transitions(st)
      next if trs.empty? # inert
      sleepable = trs.all? do |t, d|
        t.guard && t.guard.any? do |g|
          g.kind_of? Component::QMatch
        end
      end
      h[st] = true if sleepable
    end
    h
  end
end

.scratch_for(var_name) ⇒ Object

Add a scratch variable of type double to the component’s shadow. Returns the var name. The scratch var is nonpersistent and not accessible. The scratch var may be read/written by whatever flow controls var_name; the value is preserved during the continuous step.



381
382
383
384
385
# File 'lib/redshift/target/c/component-gen.rb', line 381

def scratch_for var_name
  scratch_name = "#{var_name}_scratch"
  shadow_attr :nonpersistent, scratch_name => "double #{scratch_name}"
  scratch_name
end

.setup(h = nil, &block) ⇒ Object

Register, for the current component class, the given block to be called later in the initialization of an instance, after defaults and the initialization block (the block passed to Component#new). The block is called with the world as self. Any number of blocks can be registered.



92
93
94
95
# File 'lib/redshift/syntax.rb', line 92

def setup(h = nil, &block)
  (@setup_procs ||= []) << block if block
  (@setup_map ||= {}).update make_init_value_map(h) if h
end

.src_comp(var_name) ⇒ Object



487
488
489
# File 'lib/redshift/target/c/component-gen.rb', line 487

def src_comp var_name
  "#{var_name}_src_comp"
end

.src_offset(var_name) ⇒ Object



495
496
497
# File 'lib/redshift/target/c/component-gen.rb', line 495

def src_offset var_name
  "#{var_name}_src_offset"
end

.src_type(var_name) ⇒ Object



491
492
493
# File 'lib/redshift/target/c/component-gen.rb', line 491

def src_type var_name
  "#{var_name}_src_type"
end

.start(s) ⇒ Object

Specify the starting state s of the component, as a default for the class.



63
64
65
# File 'lib/redshift/syntax.rb', line 63

def start(s)
  default {start s}
end

.state(*state_names) ⇒ Object

Define states in this component class, listed in state_names. A state name should be a string or symbol beginning with [A-Z] and consisting of alphanumeric (/\w/) characters. States are inherited.



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
# File 'lib/redshift/syntax.rb', line 100

def state(*state_names)
  state_names.flatten!
  state_names.map do |state_name|
    if state_name.kind_of? Symbol
      state_name = state_name.to_s
    else
      begin
        state_name = state_name.to_str
      rescue NoMethodError
        raise SyntaxError, "Not a valid state name: #{state_name.inspect}"
      end
    end
    
    unless state_name =~ /^[A-Z]/
      raise SyntaxError,
        "State name #{state_name.inspect} does not begin with [A-Z]."
    end
    
    begin
      val = const_get(state_name)
    rescue NameError
      attach_state(state_name)
    else
      case val
      when State
        raise NameError, "state #{state_name} already exists"
      else
        raise NameError,
          "state name '#{state_name}' is already used for a constant " +
          "of type #{val.class}."
      end
    end
  end
end

.store_wrapper(name, wrapper) ⇒ Object



101
102
103
104
105
# File 'lib/redshift/target/c/component-gen.rb', line 101

def Component.store_wrapper name, wrapper
  raise unless self == Component
  @fn_wrapper_by_name ||= {}
  @fn_wrapper_by_name[name] = wrapper
end

.strict(*var_names) ⇒ Object



187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/redshift/syntax.rb', line 187

def strict(*var_names)
  var_names.each do |var_name|
    dest = find_var_superhash(var_name)
    case dest
    when nil
     raise VarTypeError, "Variable #{var_name.inspect} not found."
    when link_variables
      var_type = link_variables[var_name].first
      attach_variables(dest, :strict, [var_name], var_type)
    else
      attach_variables(dest, :strict, [var_name])
    end
  end
end

.strict_input(*var_names) ⇒ Object



183
184
185
# File 'lib/redshift/syntax.rb', line 183

def strict_input(*var_names)
  attach_input :strict, var_names
end


161
162
163
# File 'lib/redshift/syntax.rb', line 161

def strict_link vars
  attach_link vars, :strict
end

.strictly_constant(*var_names) ⇒ Object



152
153
154
# File 'lib/redshift/syntax.rb', line 152

def strictly_constant(*var_names)
  attach_constant_variables(:strict, var_names)
end

.strictly_continuous(*var_names) ⇒ Object



139
140
141
# File 'lib/redshift/syntax.rb', line 139

def strictly_continuous(*var_names)
  attach_continuous_variables(:strict, var_names)
end

.transition(edges = {}, &block) ⇒ Object

Define transitions in this component class. Transitions are attached to all of the edges listed as src => dst. In fact, edges may also be given as [s0, s1, ...] => d and then the transition is attached to all si => d.

If no edges are specified, <tt>Enter => Enter<tt> is used. If no block is given, the Always transition is used. It is a TransitionError to omit both the edges and the block. Specifying two outgoing transitions for the same state is warned, but only when this is done within the same call to this method.

The block contains method calls to define guards, events, resets, connects, and action and post procs.

The block also can have a call to the name method, which defines the name of the transition–this is necessary for overriding the transition in a subclass.



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
# File 'lib/redshift/syntax.rb', line 510

def Component.transition(edges = {}, &block)
  e = {}
  warn = []
  
  unless edges.kind_of?(Hash)
    raise SyntaxError, "transition syntax must be 'S1 => S2, S3 => S4, ...' "
  end
  
  edges.each do |s, d|
    d = must_be_state(d)

    case s
    when Array
      s.each do |t|
        t = must_be_state(t)
        warn << t if e[t]
        e[t] = d
      end

    else
      s = must_be_state(s)
      warn << s if e[s]
      e[s] = d
    end
  end
  
  edges = e
  warn.each do |st|
    warn "Two destinations for state #{st} at #{caller[0]}."
  end

  if block
    edges = {Enter => Enter} if edges.empty?
    parser = TransitionSyntax.parse(block)
    
    if parser.events
      parser.events.each do |event_phase_item|
        event_phase_item.index = export(event_phase_item.event)[0]
            # cache index
      end
    end
    
    trans = Transition.new(parser)
    
  else
    if edges == {}
      raise TransitionError, "No transition specified."
    else
      trans = Always
    end
  end
  
  attach edges, trans
end

.var_at_offset(offset) ⇒ Object

Note: for constant and link vars. Offset is in bytes.



592
593
594
595
# File 'lib/redshift/target/c/component-gen.rb', line 592

def var_at_offset offset
  inv_offset_table[offset] or
    raise "#{offset} is not a constant or link offset in #{self}"
end

.var_countObject



369
370
371
# File 'lib/redshift/target/c/component-gen.rb', line 369

def var_count
  @var_count ||= cont_state_class.cumulative_var_count
end

Instance Method Details

#active_transitionObject

for introspection



322
# File 'lib/redshift/target/c/component-gen.rb', line 322

def active_transition; trans; end

#comp_idObject

Unique across all Worlds and Components in the process. Components are numbered in the order which this method was called on them and not necessarily in order of creation.



195
196
197
# File 'lib/redshift/component.rb', line 195

def comp_id
  @comp_id ||= Component.next_comp_id
end

#connect(input_variable, other_component, other_var, bump_d_tick = true) ⇒ Object

optimizations:

class-level caching
define connect in C?
if need_connect...


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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
# File 'lib/redshift/target/c/component-gen.rb', line 959

def connect input_variable, other_component, other_var, bump_d_tick = true
  src_comp    = self.class.src_comp(input_variable)
  src_type    = self.class.src_type(input_variable)
  src_offset  = self.class.src_offset(input_variable)

  ivs = self.class.input_variables
  unless ivs.key? input_variable
    raise TypeError, "Cannot connect non-input var: #{input_variable}."
  end
  
  strict = (ivs[input_variable] == :strict)
  connected_comp = send(src_comp)
  connected_var  = source_variable_for(input_variable)
  
  if strict and connected_comp and
      (connected_comp != other_component or
       connected_var.to_sym != other_var.to_sym)
    
    if other_component
      connected_val = connected_comp.send(connected_var)
      other_val = other_component.send(other_var)

      unless connected_val == other_val
        raise StrictnessError,
          "Cannot reconnect strict input: #{input_variable}."
      end
    
    else
      raise StrictnessError,
        "Cannot disconnect strict input: #{input_variable}."
    
    end
  end
  
  if other_var and other_component
    other_class = other_component.class
    
    case
    when other_class.continuous_variables.key?(other_var)
      other_strict = other_class.continuous_variables[other_var] == :strict
      
      type    = INPUT_CONT_VAR
      offset  = other_class.cont_state_class.vars.each {|v, desc|
        break desc.index if v.to_sym == other_var} ## table?

    when other_class.constant_variables.key?(other_var)
      other_strict = other_class.constant_variables[other_var] == :strict
      
      type    = INPUT_CONST
      offset  = other_class.offset_of_var(other_var)

    when other_class.input_variables.key?(other_var)
      other_strict = other_class.input_variables[other_var] == :strict

      type    = INPUT_INP_VAR
      offset  = other_class.offset_of_var(other_class.src_comp(other_var))

    else
      raise ArgumentError,
        "No such variable, #{other_var}, in #{other_class}."
    end
    
    if strict and not other_strict
      raise StrictnessError,
        "Cannot connect strict input, #{input_variable}, to non-strict " +
        "source: #{other_var} in #{other_component.class}."
    end

  else
    type    = INPUT_NONE
    offset  = 0
  end
  
  ## if this was in C, wouldn't need writer methods
  send("#{src_comp}=", other_component)
  send("#{src_type}=", type)
  send("#{src_offset}=", offset)
  
  world.bump_d_tick if bump_d_tick and not strict
end

#create(component_class) ⇒ Object

Create a component in the same world as this component. This method is provided for convenience. It just calls World#create.



39
40
41
42
43
44
45
# File 'lib/redshift/syntax.rb', line 39

def create(component_class)
  if block_given?
    world.create(component_class) {|c| yield c}
  else
    world.create(component_class)
  end
end

#dec_queue_ready_countObject



405
406
407
# File 'lib/redshift/component.rb', line 405

def dec_queue_ready_count
  @queue_ready_count -= 1
end

#disconnect(input_var) ⇒ Object



372
373
374
# File 'lib/redshift/component.rb', line 372

def disconnect input_var
  connect(input_var, nil, nil)
end

#flows(s = state) ⇒ Object



176
177
178
# File 'lib/redshift/meta.rb', line 176

def flows s = state
  self.class.flows s
end

#get_varname_by_offset(offset) ⇒ Object



1064
1065
1066
1067
1068
1069
1070
# File 'lib/redshift/target/c/component-gen.rb', line 1064

def get_varname_by_offset offset
  src_comp_basename = self.class.src_comp("").to_s
  varname = self.class.var_at_offset(offset).to_s
  varname.gsub!(src_comp_basename, "")
  ":#{varname}"
    ## hacky? like above...
end

#handle_strictness_error(var_idx, new_val, old_val) ⇒ Object

Called by World#step_discrete. Only for certain kinds of strictness errors.

Raises:



1163
1164
1165
1166
1167
1168
# File 'lib/redshift/target/c/component-gen.rb', line 1163

def handle_strictness_error var_idx, new_val, old_val
  var_name = cont_state.var_at_index(var_idx).name
  raise StrictnessError,
    "Transition violated strictness: var #{var_name}:" +
    " new value #{new_val} != #{old_val} in #{self.inspect}"
end

#inc_queue_ready_countObject



394
395
396
397
398
399
400
401
402
403
# File 'lib/redshift/component.rb', line 394

def inc_queue_ready_count
  if @queue_ready_count == 0 || !@queue_ready_count
    @queue_ready_count = 1
    if world.queue_sleep.delete(self)
      world.awake << self
    end
  else
    @queue_ready_count += 1
  end
end

#inspect(opts = nil) ⇒ Object



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
# File 'lib/redshift/component.rb', line 211

def inspect opts = nil
  old_inspecting = Thread.current[:inspecting]
  Thread.current[:inspecting] = self
  if opts
    float_fmt = opts["float_fmt"]
    data = opts["data"]
  end
  
  items = []
  
  unless old_inspecting == self
    # avoids inf. recursion when send(name) raises exception that
    # calls inspect again.

    if state
      items << (trans ? "#{state} => #{dest}" : state)
    end

    VAR_TYPES.each do |var_type|
      var_list = self.class.send(var_type)
      unless var_list.empty?
        strs = var_list.map {|vname,info| vname.to_s}.sort.map do |vname|
          begin
            val = send(vname)
            val = case val
            when Float
              float_fmt ? float_fmt % val : val
            when Component
              val.to_s
            else
              val.inspect
            end
            
            "#{vname} = #{val}"
            
          rescue CircularDefinitionError
            "#{vname}: CIRCULAR"
          rescue UnconnectedInputError
            "#{vname}: UNCONNECTED"
          rescue NilLinkError
            "#{vname}: NIL LINK"
          rescue => ex
            "#{vname}: #{ex.inspect}"
          end
        end
        items << strs.join(", ")
      end
    end

    if trans and (ep=trans.grep(EventPhase).first)
      strs = ep.map do |item|
        e = item.event
        "#{e}: #{send(e).inspect}"
      end
      items << strs.join(", ")
    end
    
    items << data if data
  end
  
  return "<#{[self, items.join("; ")].join(": ")}>"

ensure
  Thread.current[:inspecting] = old_inspecting
end

#insteval_proc(pr) ⇒ Object

shouldn’t be necessary



368
369
370
# File 'lib/redshift/component.rb', line 368

def insteval_proc pr
  instance_eval(&pr)
end

#outgoing_transition_dataObject



1183
1184
1185
# File 'lib/redshift/target/c/component-gen.rb', line 1183

def outgoing_transition_data
  self.class.cached_outgoing_transition_data state
end

#port(var_name) ⇒ Object

var_name can be a input var, a continuous var, or a constant var.



377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/redshift/component.rb', line 377

def port var_name
  return nil unless var_name
  @ports ||= {}
  @ports[var_name] ||= begin
    var_name = var_name.to_sym
    
    if self.class.input_variables.key? var_name
      Port.new(self, var_name, true)
    elsif self.class.continuous_variables.key? var_name or
          self.class.constant_variables.key? var_name
      Port.new(self, var_name, false)
    else
      raise "No variable #{var_name.inspect} in #{self.class.inspect}"
    end
  end
end

#restoreObject



306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/redshift/component.rb', line 306

def restore
  if respond_to?(:event_values)
    event_count = self.class.exported_events.size
      ## should cache this size, since it can't change
    self.event_values = Array.new(event_count)
    self.next_event_values = Array.new(event_count)

    event_values.freeze
    next_event_values.freeze ## should do this deeply?
  end

  yield if block_given?
  
  if state == Exit
    __set__world nil
  else
    init_flags
    update_cache
    clear_ck_strict # update_cache leaves these set assuming finishing a trans
  end
end

#source_component_for(input_variable) ⇒ Object



1040
1041
1042
# File 'lib/redshift/target/c/component-gen.rb', line 1040

def source_component_for(input_variable)
  send(self.class.src_comp(input_variable))
end

#source_variable_for(input_variable) ⇒ Object



1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
# File 'lib/redshift/target/c/component-gen.rb', line 1044

def source_variable_for(input_variable)
  comp = send(self.class.src_comp(input_variable))
  type = send(self.class.src_type(input_variable))
  offset = send(self.class.src_offset(input_variable))
  
  case type
  when INPUT_CONT_VAR
    comp.class.cont_state_class.var_at_index(offset).name
  when INPUT_CONST
    comp.class.var_at_offset(offset)
  when INPUT_INP_VAR
    src_comp_basename = self.class.src_comp("").to_s
    varname = comp.class.var_at_offset(offset).to_s
    varname.gsub(src_comp_basename, "").intern
      ## hacky?
  else
    nil
  end
end

#start(s) ⇒ Object

Specify the starting state s of the component. To be called only before the component starts running: during the default, setup, or initialization block (block passed to Component#new).

Raises:



50
51
52
53
54
55
56
57
58
# File 'lib/redshift/syntax.rb', line 50

def start(s)
  raise AlreadyStarted if state
  case s
  when State
    @start_state = s
  else
    @start_state = self.class.const_get(s.to_s)
  end
end

#statesObject



172
173
174
# File 'lib/redshift/meta.rb', line 172

def states
  self.class.states.values
end

#to_sObject



204
205
206
# File 'lib/redshift/component.rb', line 204

def to_s
  "<#{self.class} #{name || comp_id}>"
end

#transitions(s = state) ⇒ Object



180
181
182
# File 'lib/redshift/meta.rb', line 180

def transitions s = state
  self.class.all_transitions s
end