Class: Stone::AST::IntegerLiteral

Inherits:
Expression show all
Defined in:
lib/stone/ast/integer_literal.rb

Constant Summary collapse

BASES =
{
  "0b" => 2,
  "0o" => 8,
  "0x" => 16
}.freeze

Instance Attribute Summary collapse

Attributes inherited from Stone::AST

#children, #name

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ IntegerLiteral



31
32
33
34
# File 'lib/stone/ast/integer_literal.rb', line 31

def initialize(value)
  @value = value
  @name = :integer_literal
end

Instance Attribute Details

#valueObject (readonly)

Returns the value of attribute value.



29
30
31
# File 'lib/stone/ast/integer_literal.rb', line 29

def value
  @value
end

Class Method Details

.in_range?(value) ⇒ Boolean



25
26
27
# File 'lib/stone/ast/integer_literal.rb', line 25

def self.in_range?(value)
  value >= Stone::Type::Int.min && value <= Stone::Type::Int.max
end

.parse(text, location) ⇒ Object

TODO: This looks like a good place to set a good example: refactor into a Method Object.



15
16
17
18
19
20
21
22
23
# File 'lib/stone/ast/integer_literal.rb', line 15

def self.parse(text, location)
  sign = text.start_with?("-") ? -1 : 1
  unsigned_text = text.sub(/^[+-]/, "")
  base = BASES.fetch(unsigned_text[0..1], 10)
  digits = base == 10 ? unsigned_text : unsigned_text[2..]
  value = sign * Integer(digits, base)
  fail Stone::Error::Overflow.new(location:, literal: text) unless in_range?(value)
  new(value)
end

Instance Method Details

#to_llir(_builder, _mod, _scope = Stone::Scope.top_level) ⇒ Object



36
37
38
# File 'lib/stone/ast/integer_literal.rb', line 36

def to_llir(_builder, _mod, _scope = Stone::Scope.top_level)
  LLVM::Int64.from_i(@value)
end

#type(_context = nil) ⇒ Object



40
41
42
# File 'lib/stone/ast/integer_literal.rb', line 40

def type(_context = nil)
  Stone::Type::Int
end