Module: Rucc::Util

Defined in:
lib/rucc/util.rb

Defined Under Namespace

Classes: AssertError

Class Method Summary collapse

Class Method Details

.assert!(&block) ⇒ Object

Raises:



106
107
108
# File 'lib/rucc/util.rb', line 106

def assert!(&block)
  raise AssertError.new("Assertion failed!") if !block.call
end

.ceil8(n) ⇒ Integer

Parameters:

  • n (Integer)

Returns:

  • (Integer)


69
70
71
72
# File 'lib/rucc/util.rb', line 69

def ceil8(n)
  rem = n % 8
  (rem == 0) ? n : (n - rem + 8)
end

.errort!(tok, message) ⇒ Object

Parameters:

  • tok (Token)
  • message (String)

Raises:

  • (RuntimeError)


81
82
83
# File 'lib/rucc/util.rb', line 81

def errort!(tok, message)
  raise_error(token_pos(tok), "ERROR", message)
end

.quote(c) ⇒ char, NilClass

Returns nil when c is not escapetable.

Parameters:

  • c (Char)

Returns:

  • (char, NilClass)

    nil when c is not escapetable



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/rucc/util.rb', line 10

def quote(c)
  case c
  when '"'  then '\\"'
  when "\\" then '\\\\'
  when "\b" then '\\b'
  when "\f" then '\\f'
  when "\n" then '\\n'
  when "\r" then '\\r'
  when "\t" then '\\t'
  when "\v" then '\\x0b'
  else           nil
  end
end

.quote_append(b, c) ⇒ Object

@param(return) [String] b

Parameters:

  • c (Char)


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rucc/util.rb', line 26

def quote_append(b, c)
  q = quote(c)
  if q
    b << q
  elsif Libc.isprint(c)
    b << c
  else
    # TODO(south37) Fix this dirty hack.
    # In current impl, "\u00ff" (utf-8 two byte string) and "\xff" (one byte string) can not be distinguished.
    # By using byte array from the beginning, these can be expressed differently.
    if c.ord <= 0xff
      # One byte
      b << ("\\x%02x" % c.ord)
    else
      # Multi bytes
      c.bytes.each do |byte|
        b << ("\\x%02x" % byte)
      end
    end
  end
end

.quote_char(c) ⇒ Object

Parameters:

  • c (Integer)


61
62
63
64
65
# File 'lib/rucc/util.rb', line 61

def quote_char(c)
  return "\\\\" if c == '\\'.ord
  return "\\'"  if c == '\''.ord
  "%c" % c
end

.quote_cstring(str) ⇒ String

Parameters:

  • str (String)
  • c (Char)

Returns:

  • (String)


51
52
53
54
55
56
57
58
# File 'lib/rucc/util.rb', line 51

def quote_cstring(str)
  b = ""
  while (c = str[0])
    quote_append(b, c)
    str = str[1..-1]
  end
  b
end

.raise_error(pos, label, message) ⇒ Object



96
97
98
# File 'lib/rucc/util.rb', line 96

def raise_error(pos, label, message)
  raise "[#{label}] #{pos}: #{message}"
end

.token_pos(tok) ⇒ String

Parameters:

Returns:

  • (String)


87
88
89
90
91
92
93
94
# File 'lib/rucc/util.rb', line 87

def token_pos(tok)
  f = tok.file
  if !f
    return "(unknown)"
  end
  name = f.name || "(unknown)"
  "#{name}:#{tok.line}:#{tok.column}"
end