Class: StyleScript::RangeNode

Inherits:
Node
  • Object
show all
Defined in:
lib/style_script/nodes.rb

Overview

A range literal. Ranges can be used to extract portions (slices) of arrays, or to specify a range for array comprehensions.

Constant Summary

Constants inherited from Node

Node::TAB

Instance Method Summary collapse

Methods inherited from Node

#children, children, #compile, #compile_closure, #contains?, #idt, statement, #statement?, statement_only, #statement_only?, top_sensitive, #top_sensitive?, #unwrap, #write

Constructor Details

#initialize(from, to, exclusive = false) ⇒ RangeNode

Returns a new instance of RangeNode.



449
450
451
# File 'lib/style_script/nodes.rb', line 449

def initialize(from, to, exclusive=false)
  @from, @to, @exclusive = from, to, exclusive
end

Instance Method Details

#compile_array(o) ⇒ Object

Expand the range into the equivalent array, if it’s not being used as part of a comprehension, slice, or splice. TODO: This generates pretty ugly code … shrink it.



478
479
480
481
482
# File 'lib/style_script/nodes.rb', line 478

def compile_array(o)
  body = Expressions.wrap(LiteralNode.wrap('i'))
  arr  = Expressions.wrap(ForNode.new(body, {:source => ValueNode.new(self)}, Value.new('i')))
  ParentheticalNode.new(CallNode.new(CodeNode.new([], arr))).compile(o)
end

#compile_node(o) ⇒ Object



464
465
466
467
468
469
470
471
472
473
# File 'lib/style_script/nodes.rb', line 464

def compile_node(o)
  return compile_array(o) unless o[:index]
  idx, step = o.delete(:index), o.delete(:step)
  vars      = "#{idx}=#{@from_var}"
  step      = step ? step.compile(o) : '1'
  equals    = @exclusive ? '' : '='
  compare   = "(#{@from_var} <= #{@to_var} ? #{idx} <#{equals} #{@to_var} : #{idx} >#{equals} #{@to_var})"
  incr      = "(#{@from_var} <= #{@to_var} ? #{idx} += #{step} : #{idx} -= #{step})"
  write("#{vars}; #{compare}; #{incr}")
end

#compile_variables(o) ⇒ Object



457
458
459
460
461
462
# File 'lib/style_script/nodes.rb', line 457

def compile_variables(o)
  @indent = o[:indent]
  @from_var, @to_var = o[:scope].free_variable, o[:scope].free_variable
  from_val,  to_val  = @from.compile(o), @to.compile(o)
  write("#{@from_var} = #{from_val}; #{@to_var} = #{to_val};\n#{idt}")
end

#exclusive?Boolean

Returns:

  • (Boolean)


453
454
455
# File 'lib/style_script/nodes.rb', line 453

def exclusive?
  @exclusive
end