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, SingletonShadowClass, 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.



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/redshift/component.rb', line 274

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.



130
131
132
# File 'lib/redshift/component.rb', line 130

def name
  @name
end

#start_stateObject (readonly)

Returns the value of attribute start_state.



129
130
131
# File 'lib/redshift/component.rb', line 129

def start_state
  @start_state
end

Class Method Details

._offset_tableObject



561
562
563
# File 'lib/redshift/target/c/component-gen.rb', line 561

def _offset_table
  {}
end

.add_flow(h) ⇒ Object

state, var

> flow_wrapper_subclass, …



345
346
347
# File 'lib/redshift/target/c/component-gen.rb', line 345

def add_flow h      # [state, var] => flow_wrapper_subclass, ...
  flow_hash.update h
end

.add_var_to_offset_table(var_name) ⇒ Object



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

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



154
155
156
# File 'lib/redshift/meta.rb', line 154

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



149
150
151
# File 'lib/redshift/meta.rb', line 149

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



158
159
160
161
162
# File 'lib/redshift/meta.rb', line 158

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



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

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)


1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
# File 'lib/redshift/target/c/component-gen.rb', line 1082

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



646
647
648
649
650
651
652
653
# File 'lib/redshift/target/c/component-gen.rb', line 646

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



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

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



763
764
765
766
767
768
769
770
771
772
773
774
775
776
# File 'lib/redshift/target/c/component-gen.rb', line 763

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



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

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



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

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



384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# File 'lib/redshift/target/c/component-gen.rb', line 384

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



655
656
657
658
659
# File 'lib/redshift/target/c/component-gen.rb', line 655

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



877
878
879
880
881
882
883
884
885
886
887
# File 'lib/redshift/target/c/component-gen.rb', line 877

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

.define_eventsObject



553
554
555
556
557
558
559
# File 'lib/redshift/target/c/component-gen.rb', line 553

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_flows(state) ⇒ Object



673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
# File 'lib/redshift/target/c/component-gen.rb', line 673

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

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

    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
  end
end

.define_guard(expr) ⇒ Object



704
705
706
707
708
# File 'lib/redshift/target/c/component-gen.rb', line 704

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

.define_guards(guards) ⇒ Object



716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
# File 'lib/redshift/target/c/component-gen.rb', line 716

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
      if HAVE_DEFINE_METHOD
        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
      else
        g # a proc is slower than a method when called from step_discrete
      end
    
    when Class
      if g < GuardWrapper
        g
      else
        raise "What is #{g.inspect}?"
      end

    when String
      define_guard(g)
    
    else
      raise "What is #{g.inspect}?"
    end
  end
end

.define_input(kind, var_names) ⇒ Object



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

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



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

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


605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# File 'lib/redshift/target/c/component-gen.rb', line 605

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



778
779
780
781
782
# File 'lib/redshift/target/c/component-gen.rb', line 778

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

.define_reset_constant(var, expr, phase) ⇒ Object



829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
# File 'lib/redshift/target/c/component-gen.rb', line 829

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.instance, 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



802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
# File 'lib/redshift/target/c/component-gen.rb', line 802

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.instance
    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


855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
# File 'lib/redshift/target/c/component-gen.rb', line 855

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.instance, var, type]
    end

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

.define_resets(phase) ⇒ Object



784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
# File 'lib/redshift/target/c/component-gen.rb', line 784

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



1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
# File 'lib/redshift/target/c/component-gen.rb', line 1237

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_0)[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++ > 100) {
          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



755
756
757
758
759
760
761
# File 'lib/redshift/target/c/component-gen.rb', line 755

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



889
890
891
892
893
894
895
896
897
898
899
# File 'lib/redshift/target/c/component-gen.rb', line 889

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



335
336
337
338
339
340
# File 'lib/redshift/component.rb', line 335

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



342
343
344
345
346
347
348
349
350
# File 'lib/redshift/component.rb', line 342

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



352
353
354
355
356
357
358
359
360
361
362
# File 'lib/redshift/component.rb', line 352

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

.find_var_superhash(var_name) ⇒ Object



164
165
166
167
# File 'lib/redshift/meta.rb', line 164

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"


477
478
479
480
481
482
483
# File 'lib/redshift/syntax.rb', line 477

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.



341
342
343
# File 'lib/redshift/target/c/component-gen.rb', line 341

def flow_hash
  @flow_hash ||= {}
end

.flow_tableObject



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

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_class in flow_hash
      (ft[state] ||= [])[var.index] = flow_class.instance
    end
    @flow_table = ft
  end
  @flow_table
end

.flow_wrapper(flow, state) ⇒ Object



698
699
700
701
702
# File 'lib/redshift/target/c/component-gen.rb', line 698

def flow_wrapper flow, state
  @flow_wrapper_hash ||= {}
  @flow_wrapper_hash[ [flow.var, flow.formula] ] ||=
    flow.flow_wrapper(self, state)
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



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

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



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

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



185
186
187
# File 'lib/redshift/component.rb', line 185

def Component.literal val
  Literal.new val
end

.make_guard_method_nameObject



710
711
712
713
714
# File 'lib/redshift/target/c/component-gen.rb', line 710

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



557
558
559
560
561
562
563
564
565
566
567
# File 'lib/redshift/syntax.rb', line 557

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



197
198
199
# File 'lib/redshift/component.rb', line 197

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.



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

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



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

def offset_table
  @offset_table ||= _offset_table
end

.offset_table_methodObject



585
586
587
588
589
590
591
592
593
# File 'lib/redshift/target/c/component-gen.rb', line 585

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

def outgoing_transition_data s
  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



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

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



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

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.



378
379
380
381
382
# File 'lib/redshift/target/c/component-gen.rb', line 378

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



484
485
486
# File 'lib/redshift/target/c/component-gen.rb', line 484

def src_comp var_name
  "#{var_name}_src_comp"
end

.src_offset(var_name) ⇒ Object



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

def src_offset var_name
  "#{var_name}_src_offset"
end

.src_type(var_name) ⇒ Object



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

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

.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.



502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
# File 'lib/redshift/syntax.rb', line 502

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.



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

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

.var_countObject



366
367
368
# File 'lib/redshift/target/c/component-gen.rb', line 366

def var_count
  @var_count ||= cont_state_class.cumulative_var_count
end

Instance Method Details

#active_transitionObject

for introspection



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

def active_transition; trans; end

#clear_ck_strictObject

end # if need connect



1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
# File 'lib/redshift/target/c/component-gen.rb', line 1057

define_c_method :clear_ck_strict do
  declare :locals => %{
    ContVar    *vars;
    long        var_count;
    long        i;
  }
  body %{
    vars = (ContVar *)&FIRST_CONT_VAR(shadow);
    var_count = shadow->var_count;

    for (i = 0; i < var_count; i++) {
      vars[i].ck_strict = 0;
    }
  }
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.



192
193
194
# File 'lib/redshift/component.rb', line 192

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...


943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
# File 'lib/redshift/target/c/component-gen.rb', line 943

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



402
403
404
# File 'lib/redshift/component.rb', line 402

def dec_queue_ready_count
  @queue_ready_count -= 1
end

#disconnect(input_var) ⇒ Object



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

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

#flows(s = state) ⇒ Object



174
175
176
# File 'lib/redshift/meta.rb', line 174

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

#get_varname_by_offset(offset) ⇒ Object



1048
1049
1050
1051
1052
1053
1054
# File 'lib/redshift/target/c/component-gen.rb', line 1048

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:



1075
1076
1077
1078
1079
1080
# File 'lib/redshift/target/c/component-gen.rb', line 1075

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



391
392
393
394
395
396
397
398
399
400
# File 'lib/redshift/component.rb', line 391

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



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/redshift/component.rb', line 208

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



365
366
367
# File 'lib/redshift/component.rb', line 365

def insteval_proc pr
  instance_eval(&pr)
end

#outgoing_transition_dataObject



1095
1096
1097
# File 'lib/redshift/target/c/component-gen.rb', line 1095

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.



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

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



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

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



1024
1025
1026
# File 'lib/redshift/target/c/component-gen.rb', line 1024

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

#source_variable_for(input_variable) ⇒ Object



1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
# File 'lib/redshift/target/c/component-gen.rb', line 1028

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



170
171
172
# File 'lib/redshift/meta.rb', line 170

def states
  self.class.states.values
end

#to_sObject



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

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

#transitions(s = state) ⇒ Object



178
179
180
# File 'lib/redshift/meta.rb', line 178

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