repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/time/timespan.rb | lib/puppet/pops/time/timespan.rb | # frozen_string_literal: true
require_relative '../../../puppet/concurrent/thread_local_singleton'
module Puppet::Pops
module Time
NSECS_PER_USEC = 1000
NSECS_PER_MSEC = NSECS_PER_USEC * 1000
NSECS_PER_SEC = NSECS_PER_MSEC * 1000
NSECS_PER_MIN = NSECS_PER_SEC * 60
NSECS_PER_HOUR = NSECS_PER_MIN * 60
NSECS_PER_DAY = NSECS_PER_HOUR * 24
KEY_STRING = 'string'
KEY_FORMAT = 'format'
KEY_NEGATIVE = 'negative'
KEY_DAYS = 'days'
KEY_HOURS = 'hours'
KEY_MINUTES = 'minutes'
KEY_SECONDS = 'seconds'
KEY_MILLISECONDS = 'milliseconds'
KEY_MICROSECONDS = 'microseconds'
KEY_NANOSECONDS = 'nanoseconds'
# TimeData is a Numeric that stores its value internally as nano-seconds but will be considered to be seconds and fractions of
# seconds when used in arithmetic or comparison with other Numeric types.
#
class TimeData < Numeric
include LabelProvider
attr_reader :nsecs
def initialize(nanoseconds)
@nsecs = nanoseconds
end
def <=>(o)
case o
when self.class
@nsecs <=> o.nsecs
when Integer
to_int <=> o
when Float
to_f <=> o
else
nil
end
end
def label(o)
Utils.name_to_segments(o.class.name).last
end
# @return [Float] the number of seconds
def to_f
@nsecs.fdiv(NSECS_PER_SEC)
end
# @return [Integer] the number of seconds with fraction part truncated
def to_int
@nsecs / NSECS_PER_SEC
end
def to_i
to_int
end
# @return [Complex] short for `#to_f.to_c`
def to_c
to_f.to_c
end
# @return [Rational] initial numerator is nano-seconds and denominator is nano-seconds per second
def to_r
Rational(@nsecs, NSECS_PER_SEC)
end
undef_method :phase, :polar, :rect, :rectangular
end
class Timespan < TimeData
def self.from_fields(negative, days, hours, minutes, seconds, milliseconds = 0, microseconds = 0, nanoseconds = 0)
ns = (((((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000 + milliseconds) * 1000 + microseconds) * 1000 + nanoseconds
new(negative ? -ns : ns)
end
def self.from_hash(hash)
hash.include?('string') ? from_string_hash(hash) : from_fields_hash(hash)
end
def self.from_string_hash(hash)
parse(hash[KEY_STRING], hash[KEY_FORMAT] || Format::DEFAULTS)
end
def self.from_fields_hash(hash)
from_fields(
hash[KEY_NEGATIVE] || false,
hash[KEY_DAYS] || 0,
hash[KEY_HOURS] || 0,
hash[KEY_MINUTES] || 0,
hash[KEY_SECONDS] || 0,
hash[KEY_MILLISECONDS] || 0,
hash[KEY_MICROSECONDS] || 0,
hash[KEY_NANOSECONDS] || 0
)
end
def self.parse(str, format = Format::DEFAULTS)
if format.is_a?(::Array)
format.each do |fmt|
fmt = FormatParser.singleton.parse_format(fmt) unless fmt.is_a?(Format)
begin
return fmt.parse(str)
rescue ArgumentError
end
end
raise ArgumentError, _("Unable to parse '%{str}' using any of the formats %{formats}") % { str: str, formats: format.join(', ') }
end
format = FormatParser.singleton.parse_format(format) unless format.is_a?(Format)
format.parse(str)
end
# @return [true] if the stored value is negative
def negative?
@nsecs < 0
end
def +(o)
case o
when Timestamp
Timestamp.new(@nsecs + o.nsecs)
when Timespan
Timespan.new(@nsecs + o.nsecs)
when Integer, Float
# Add seconds
Timespan.new(@nsecs + (o * NSECS_PER_SEC).to_i)
else
raise ArgumentError, _("%{klass} cannot be added to a Timespan") % { klass: a_an_uc(o) } unless o.is_a?(Timespan)
end
end
def -(o)
case o
when Timespan
Timespan.new(@nsecs - o.nsecs)
when Integer, Float
# Subtract seconds
Timespan.new(@nsecs - (o * NSECS_PER_SEC).to_i)
else
raise ArgumentError, _("%{klass} cannot be subtracted from a Timespan") % { klass: a_an_uc(o) }
end
end
def -@
Timespan.new(-@nsecs)
end
def *(o)
case o
when Integer, Float
Timespan.new((@nsecs * o).to_i)
else
raise ArgumentError, _("A Timestamp cannot be multiplied by %{klass}") % { klass: a_an(o) }
end
end
def divmod(o)
case o
when Integer
to_i.divmod(o)
when Float
to_f.divmod(o)
else
raise ArgumentError, _("Can not do modulus on a Timespan using a %{klass}") % { klass: a_an(o) }
end
end
def modulo(o)
divmod(o)[1]
end
def %(o)
modulo(o)
end
def div(o)
case o
when Timespan
# Timespan/Timespan yields a Float
@nsecs.fdiv(o.nsecs)
when Integer, Float
Timespan.new(@nsecs.div(o))
else
raise ArgumentError, _("A Timespan cannot be divided by %{klass}") % { klass: a_an(o) }
end
end
def /(o)
div(o)
end
# @return [Integer] a positive integer denoting the number of days
def days
total_days
end
# @return [Integer] a positive integer, 0 - 23 denoting hours of day
def hours
total_hours % 24
end
# @return [Integer] a positive integer, 0 - 59 denoting minutes of hour
def minutes
total_minutes % 60
end
# @return [Integer] a positive integer, 0 - 59 denoting seconds of minute
def seconds
total_seconds % 60
end
# @return [Integer] a positive integer, 0 - 999 denoting milliseconds of second
def milliseconds
total_milliseconds % 1000
end
# @return [Integer] a positive integer, 0 - 999.999.999 denoting nanoseconds of second
def nanoseconds
total_nanoseconds % NSECS_PER_SEC
end
# Formats this timestamp into a string according to the given `format`
#
# @param [String,Format] format The format to use when producing the string
# @return [String] the string representing the formatted timestamp
# @raise [ArgumentError] if the format is a string with illegal format characters
# @api public
def format(format)
format = FormatParser.singleton.parse_format(format) unless format.is_a?(Format)
format.format(self)
end
# Formats this timestamp into a string according to {Format::DEFAULTS[0]}
#
# @return [String] the string representing the formatted timestamp
# @api public
def to_s
format(Format::DEFAULTS[0])
end
def to_hash(compact = false)
result = {}
n = nanoseconds
if compact
s = total_seconds
result[KEY_SECONDS] = negative? ? -s : s
result[KEY_NANOSECONDS] = negative? ? -n : n unless n == 0
else
add_unless_zero(result, KEY_DAYS, days)
add_unless_zero(result, KEY_HOURS, hours)
add_unless_zero(result, KEY_MINUTES, minutes)
add_unless_zero(result, KEY_SECONDS, seconds)
unless n == 0
add_unless_zero(result, KEY_NANOSECONDS, n % 1000)
n /= 1000
add_unless_zero(result, KEY_MICROSECONDS, n % 1000)
add_unless_zero(result, KEY_MILLISECONDS, n / 1000)
end
result[KEY_NEGATIVE] = true if negative?
end
result
end
def add_unless_zero(result, key, value)
result[key] = value unless value == 0
end
private :add_unless_zero
# @api private
def total_days
total_nanoseconds / NSECS_PER_DAY
end
# @api private
def total_hours
total_nanoseconds / NSECS_PER_HOUR
end
# @api private
def total_minutes
total_nanoseconds / NSECS_PER_MIN
end
# @api private
def total_seconds
total_nanoseconds / NSECS_PER_SEC
end
# @api private
def total_milliseconds
total_nanoseconds / NSECS_PER_MSEC
end
# @api private
def total_microseconds
total_nanoseconds / NSECS_PER_USEC
end
# @api private
def total_nanoseconds
@nsecs.abs
end
# Represents a compiled Timestamp format. The format is used both when parsing a timestamp
# in string format and when producing a string from a timestamp instance.
#
class Format
# A segment is either a string that will be represented literally in the formatted timestamp
# or a value that corresponds to one of the possible format characters.
class Segment
def append_to(bld, ts)
raise NotImplementedError, "'#{self.class.name}' should implement #append_to"
end
def append_regexp(bld, ts)
raise NotImplementedError, "'#{self.class.name}' should implement #append_regexp"
end
def multiplier
raise NotImplementedError, "'#{self.class.name}' should implement #multiplier"
end
end
class LiteralSegment < Segment
def append_regexp(bld)
bld << "(#{Regexp.escape(@literal)})"
end
def initialize(literal)
@literal = literal
end
def append_to(bld, ts)
bld << @literal
end
def concat(codepoint)
@literal.concat(codepoint)
end
def nanoseconds
0
end
end
class ValueSegment < Segment
def initialize(padchar, width, default_width)
@use_total = false
@padchar = padchar
@width = width
@default_width = default_width
@format = create_format
end
def create_format
case @padchar
when nil
'%d'
when ' '
"%#{@width || @default_width}d"
else
"%#{@padchar}#{@width || @default_width}d"
end
end
def append_regexp(bld)
if @width.nil?
case @padchar
when nil
bld << (use_total? ? '([0-9]+)' : "([0-9]{1,#{@default_width}})")
when '0'
bld << (use_total? ? '([0-9]+)' : "([0-9]{1,#{@default_width}})")
else
bld << (use_total? ? '\s*([0-9]+)' : "([0-9\\s]{1,#{@default_width}})")
end
else
case @padchar
when nil
bld << "([0-9]{1,#{@width}})"
when '0'
bld << "([0-9]{#{@width}})"
else
bld << "([0-9\\s]{#{@width}})"
end
end
end
def nanoseconds(group)
group.to_i * multiplier
end
def multiplier
0
end
def set_use_total
@use_total = true
end
def use_total?
@use_total
end
def append_value(bld, n)
bld << sprintf(@format, n)
end
end
class DaySegment < ValueSegment
def initialize(padchar, width)
super(padchar, width, 1)
end
def multiplier
NSECS_PER_DAY
end
def append_to(bld, ts)
append_value(bld, ts.days)
end
end
class HourSegment < ValueSegment
def initialize(padchar, width)
super(padchar, width, 2)
end
def multiplier
NSECS_PER_HOUR
end
def append_to(bld, ts)
append_value(bld, use_total? ? ts.total_hours : ts.hours)
end
end
class MinuteSegment < ValueSegment
def initialize(padchar, width)
super(padchar, width, 2)
end
def multiplier
NSECS_PER_MIN
end
def append_to(bld, ts)
append_value(bld, use_total? ? ts.total_minutes : ts.minutes)
end
end
class SecondSegment < ValueSegment
def initialize(padchar, width)
super(padchar, width, 2)
end
def multiplier
NSECS_PER_SEC
end
def append_to(bld, ts)
append_value(bld, use_total? ? ts.total_seconds : ts.seconds)
end
end
# Class that assumes that leading zeroes are significant and that trailing zeroes are not and left justifies when formatting.
# Applicable after a decimal point, and hence to the %L and %N formats.
class FragmentSegment < ValueSegment
def nanoseconds(group)
# Using %L or %N to parse a string only makes sense when they are considered to be fractions. Using them
# as a total quantity would introduce ambiguities.
raise ArgumentError, _('Format specifiers %L and %N denotes fractions and must be used together with a specifier of higher magnitude') if use_total?
n = group.to_i
p = 9 - group.length
p <= 0 ? n : n * 10**p
end
def create_format
if @padchar.nil?
'%d'
else
"%-#{@width || @default_width}d"
end
end
def append_value(bld, n)
# Strip trailing zeroes when default format is used
n = n.to_s.sub(/\A([0-9]+?)0*\z/, '\1').to_i unless use_total? || @padchar == '0'
super(bld, n)
end
end
class MilliSecondSegment < FragmentSegment
def initialize(padchar, width)
super(padchar, width, 3)
end
def multiplier
NSECS_PER_MSEC
end
def append_to(bld, ts)
append_value(bld, use_total? ? ts.total_milliseconds : ts.milliseconds)
end
end
class NanoSecondSegment < FragmentSegment
def initialize(padchar, width)
super(padchar, width, 9)
end
def multiplier
width = @width || @default_width
if width < 9
10**(9 - width)
else
1
end
end
def append_to(bld, ts)
ns = ts.total_nanoseconds
width = @width || @default_width
if width < 9
# Truncate digits to the right, i.e. let %6N reflect microseconds
ns /= 10**(9 - width)
ns %= 10**width unless use_total?
else
ns %= NSECS_PER_SEC unless use_total?
end
append_value(bld, ns)
end
end
def initialize(format, segments)
@format = format.freeze
@segments = segments.freeze
end
def format(timespan)
bld = timespan.negative? ? '-'.dup : ''.dup
@segments.each { |segment| segment.append_to(bld, timespan) }
bld
end
def parse(timespan)
md = regexp.match(timespan)
raise ArgumentError, _("Unable to parse '%{timespan}' using format '%{format}'") % { timespan: timespan, format: @format } if md.nil?
nanoseconds = 0
md.captures.each_with_index do |group, index|
segment = @segments[index]
next if segment.is_a?(LiteralSegment)
group.lstrip!
raise ArgumentError, _("Unable to parse '%{timespan}' using format '%{format}'") % { timespan: timespan, format: @format } unless group =~ /\A[0-9]+\z/
nanoseconds += segment.nanoseconds(group)
end
Timespan.new(timespan.start_with?('-') ? -nanoseconds : nanoseconds)
end
def to_s
@format
end
private
def regexp
@regexp ||= build_regexp
end
def build_regexp
bld = '\A-?'.dup
@segments.each { |segment| segment.append_regexp(bld) }
bld << '\z'
Regexp.new(bld)
end
end
# Parses a string into a Timestamp::Format instance
class FormatParser
extend Puppet::Concurrent::ThreadLocalSingleton
def initialize
@formats = Hash.new { |hash, str| hash[str] = internal_parse(str) }
end
def parse_format(format)
@formats[format]
end
private
NSEC_MAX = 0
MSEC_MAX = 1
SEC_MAX = 2
MIN_MAX = 3
HOUR_MAX = 4
DAY_MAX = 5
SEGMENT_CLASS_BY_ORDINAL = [
Format::NanoSecondSegment, Format::MilliSecondSegment, Format::SecondSegment, Format::MinuteSegment, Format::HourSegment, Format::DaySegment
]
def bad_format_specifier(format, start, position)
_("Bad format specifier '%{expression}' in '%{format}', at position %{position}") % { expression: format[start, position - start], format: format, position: position }
end
def append_literal(bld, codepoint)
if bld.empty? || !bld.last.is_a?(Format::LiteralSegment)
bld << Format::LiteralSegment.new(''.dup.concat(codepoint))
else
bld.last.concat(codepoint)
end
end
# States used by the #internal_parser function
STATE_LITERAL = 0 # expects literal or '%'
STATE_PAD = 1 # expects pad, width, or format character
STATE_WIDTH = 2 # expects width, or format character
def internal_parse(str)
bld = []
raise ArgumentError, _('Format must be a String') unless str.is_a?(String)
highest = -1
state = STATE_LITERAL
padchar = '0'
width = nil
position = -1
fstart = 0
str.each_codepoint do |codepoint|
position += 1
if state == STATE_LITERAL
if codepoint == 0x25 # '%'
state = STATE_PAD
fstart = position
padchar = '0'
width = nil
else
append_literal(bld, codepoint)
end
next
end
case codepoint
when 0x25 # '%'
append_literal(bld, codepoint)
state = STATE_LITERAL
when 0x2D # '-'
raise ArgumentError, bad_format_specifier(str, fstart, position) unless state == STATE_PAD
padchar = nil
state = STATE_WIDTH
when 0x5F # '_'
raise ArgumentError, bad_format_specifier(str, fstart, position) unless state == STATE_PAD
padchar = ' '
state = STATE_WIDTH
when 0x44 # 'D'
highest = DAY_MAX
bld << Format::DaySegment.new(padchar, width)
state = STATE_LITERAL
when 0x48 # 'H'
highest = HOUR_MAX unless highest > HOUR_MAX
bld << Format::HourSegment.new(padchar, width)
state = STATE_LITERAL
when 0x4D # 'M'
highest = MIN_MAX unless highest > MIN_MAX
bld << Format::MinuteSegment.new(padchar, width)
state = STATE_LITERAL
when 0x53 # 'S'
highest = SEC_MAX unless highest > SEC_MAX
bld << Format::SecondSegment.new(padchar, width)
state = STATE_LITERAL
when 0x4C # 'L'
highest = MSEC_MAX unless highest > MSEC_MAX
bld << Format::MilliSecondSegment.new(padchar, width)
state = STATE_LITERAL
when 0x4E # 'N'
highest = NSEC_MAX unless highest > NSEC_MAX
bld << Format::NanoSecondSegment.new(padchar, width)
state = STATE_LITERAL
else # only digits allowed at this point
raise ArgumentError, bad_format_specifier(str, fstart, position) unless codepoint >= 0x30 && codepoint <= 0x39
if state == STATE_PAD && codepoint == 0x30
padchar = '0'
else
n = codepoint - 0x30
if width.nil?
width = n
else
width = width * 10 + n
end
end
state = STATE_WIDTH
end
end
raise ArgumentError, bad_format_specifier(str, fstart, position) unless state == STATE_LITERAL
unless highest == -1
hc = SEGMENT_CLASS_BY_ORDINAL[highest]
bld.find { |s| s.instance_of?(hc) }.set_use_total
end
Format.new(str, bld)
end
end
class Format
DEFAULTS = ['%D-%H:%M:%S.%-N', '%H:%M:%S.%-N', '%M:%S.%-N', '%S.%-N', '%D-%H:%M:%S', '%H:%M:%S', '%D-%H:%M', '%S'].map { |str| FormatParser.singleton.parse_format(str) }
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/time/timestamp.rb | lib/puppet/pops/time/timestamp.rb | # frozen_string_literal: true
module Puppet::Pops
module Time
class Timestamp < TimeData
DEFAULT_FORMATS_WO_TZ = ['%FT%T.%N', '%FT%T', '%F %T.%N', '%F %T', '%F']
DEFAULT_FORMATS = ['%FT%T.%N %Z', '%FT%T %Z', '%F %T.%N %Z', '%F %T %Z', '%F %Z'] + DEFAULT_FORMATS_WO_TZ
CURRENT_TIMEZONE = 'current'
KEY_TIMEZONE = 'timezone'
# Converts a timezone that strptime can parse using '%z' into '-HH:MM' or '+HH:MM'
# @param [String] tz the timezone to convert
# @return [String] the converted timezone
#
# @api private
def self.convert_timezone(tz)
if tz =~ /\A[+-]\d\d:\d\d\z/
tz
else
offset = utc_offset(tz) / 60
if offset < 0
offset = offset.abs
sprintf('-%2.2d:%2.2d', offset / 60, offset % 60)
else
sprintf('+%2.2d:%2.2d', offset / 60, offset % 60)
end
end
end
# Returns the zone offset from utc for the given `timezone`
# @param [String] timezone the timezone to get the offset for
# @return [Integer] the timezone offset, in seconds
#
# @api private
def self.utc_offset(timezone)
if CURRENT_TIMEZONE.casecmp(timezone) == 0
::Time.now.utc_offset
else
hash = DateTime._strptime(timezone, '%z')
offset = hash.nil? ? nil : hash[:offset]
raise ArgumentError, _("Illegal timezone '%{timezone}'") % { timezone: timezone } if offset.nil?
offset
end
end
# Formats a ruby Time object using the given timezone
def self.format_time(format, time, timezone)
unless timezone.nil? || timezone.empty?
time = time.localtime(convert_timezone(timezone))
end
time.strftime(format)
end
def self.now
from_time(::Time.now)
end
def self.from_time(t)
new(t.tv_sec * NSECS_PER_SEC + t.tv_nsec)
end
def self.from_hash(args_hash)
parse(args_hash[KEY_STRING], args_hash[KEY_FORMAT], args_hash[KEY_TIMEZONE])
end
def self.parse(str, format = :default, timezone = nil)
has_timezone = !(timezone.nil? || timezone.empty? || timezone == :default)
if format.nil? || format == :default
format = has_timezone ? DEFAULT_FORMATS_WO_TZ : DEFAULT_FORMATS
end
parsed = nil
if format.is_a?(Array)
format.each do |fmt|
parsed = DateTime._strptime(str, fmt)
next if parsed.nil?
if parsed.include?(:leftover) || (has_timezone && parsed.include?(:zone))
parsed = nil
next
end
break
end
if parsed.nil?
raise ArgumentError, _(
"Unable to parse '%{str}' using any of the formats %{formats}"
) % { str: str, formats: format.join(', ') }
end
else
parsed = DateTime._strptime(str, format)
if parsed.nil? || parsed.include?(:leftover)
raise ArgumentError, _("Unable to parse '%{str}' using format '%{format}'") % { str: str, format: format }
end
if has_timezone && parsed.include?(:zone)
raise ArgumentError, _(
'Using a Timezone designator in format specification is mutually exclusive to providing an explicit timezone argument'
)
end
end
unless has_timezone
timezone = parsed[:zone]
has_timezone = !timezone.nil?
end
fraction = parsed[:sec_fraction]
# Convert msec rational found in _strptime hash to usec
fraction *= 1_000_000 unless fraction.nil?
# Create the Time instance and adjust for timezone
parsed_time = ::Time.utc(parsed[:year], parsed[:mon], parsed[:mday], parsed[:hour], parsed[:min], parsed[:sec], fraction)
parsed_time -= utc_offset(timezone) if has_timezone
# Convert to Timestamp
from_time(parsed_time)
end
undef_method :-@, :+@, :div, :fdiv, :abs, :abs2, :magnitude # does not make sense on a Timestamp
if method_defined?(:negative?)
undef_method :negative?, :positive?
end
if method_defined?(:%)
undef_method :%, :modulo, :divmod
end
def +(o)
case o
when Timespan
Timestamp.new(@nsecs + o.nsecs)
when Integer, Float
Timestamp.new(@nsecs + (o * NSECS_PER_SEC).to_i)
else
raise ArgumentError, _("%{klass} cannot be added to a Timestamp") % { klass: a_an_uc(o) }
end
end
def -(o)
case o
when Timestamp
# Diff between two timestamps is a timespan
Timespan.new(@nsecs - o.nsecs)
when Timespan
Timestamp.new(@nsecs - o.nsecs)
when Integer, Float
# Subtract seconds
Timestamp.new(@nsecs - (o * NSECS_PER_SEC).to_i)
else
raise ArgumentError, _("%{klass} cannot be subtracted from a Timestamp") % { klass: a_an_uc(o) }
end
end
def format(format, timezone = nil)
self.class.format_time(format, to_time, timezone)
end
def to_s
format(DEFAULT_FORMATS[0])
end
def to_time
::Time.at(to_r).utc
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/type_assertion_error.rb | lib/puppet/pops/types/type_assertion_error.rb | # frozen_string_literal: true
module Puppet::Pops::Types
# Raised when an assertion of actual type against an expected type fails.
#
class TypeAssertionError < Puppet::Error
# Returns the expected type
# @return [PAnyType] expected type
attr_reader :expected_type
# Returns the actual type
# @return [PAnyType] actual type
attr_reader :actual_type
# Creates a new instance with a default message, expected, and actual types,
#
# @param message [String] The default message
# @param expected_type [PAnyType] The expected type
# @param actual_type [PAnyType] The actual type
#
def initialize(message, expected_type, actual_type)
super(message)
@expected_type = expected_type
@actual_type = actual_type
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/type_factory.rb | lib/puppet/pops/types/type_factory.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
# Helper module that makes creation of type objects simpler.
# @api public
#
module TypeFactory
@type_calculator = TypeCalculator.singleton
# Clears caches - used when testing
def self.clear
# these types are cached and needs to be nulled as the representation may change if loaders are cleared
@data_t = nil
@rich_data_t = nil
@rich_data_key_t = nil
@array_of_data_t = nil
@hash_of_data_t = nil
@error_t = nil
@task_t = nil
@deferred_t = nil
end
# Produces the Integer type
# @api public
#
def self.integer
PIntegerType::DEFAULT
end
# Produces an Integer range type
# @api public
#
def self.range(from, to)
# optimize eq with symbol (faster when it is left)
from = :default == from if from == 'default'
to = :default if to == 'default'
PIntegerType.new(from, to)
end
# Produces a Float range type
# @api public
#
def self.float_range(from, to)
# optimize eq with symbol (faster when it is left)
from = Float(from) unless :default == from || from.nil?
to = Float(to) unless :default == to || to.nil?
PFloatType.new(from, to)
end
# Produces the Float type
# @api public
#
def self.float
PFloatType::DEFAULT
end
# Produces the Sensitive type
# @api public
#
def self.sensitive(type = nil)
PSensitiveType.new(type)
end
# Produces the Numeric type
# @api public
#
def self.numeric
PNumericType::DEFAULT
end
# Produces the Init type
# @api public
def self.init(*args)
case args.size
when 0
PInitType::DEFAULT
when 1
type = args[0]
type.nil? ? PInitType::DEFAULT : PInitType.new(type, EMPTY_ARRAY)
else
type = args.shift
PInitType.new(type, args)
end
end
# Produces the Iterable type
# @api public
#
def self.iterable(elem_type = nil)
elem_type.nil? ? PIterableType::DEFAULT : PIterableType.new(elem_type)
end
# Produces the Iterator type
# @api public
#
def self.iterator(elem_type = nil)
elem_type.nil? ? PIteratorType::DEFAULT : PIteratorType.new(elem_type)
end
# Produces a string representation of the type
# @api public
#
def self.label(t)
@type_calculator.string(t)
end
# Produces the String type based on nothing, a string value that becomes an exact match constraint, or a parameterized
# Integer type that constraints the size.
#
# @api public
#
def self.string(size_type_or_value = nil, *deprecated_second_argument)
if deprecated_second_argument.empty?
size_type_or_value.nil? ? PStringType::DEFAULT : PStringType.new(size_type_or_value)
else
if Puppet[:strict] != :off
# TRANSLATORS 'TypeFactory#string' is a class and method name and should not be translated
message = _("Passing more than one argument to TypeFactory#string is deprecated")
Puppet.warn_once('deprecations', "TypeFactory#string_multi_args", message)
end
deprecated_second_argument.size == 1 ? PStringType.new(deprecated_second_argument[0]) : PEnumType.new(*deprecated_second_argument)
end
end
# Produces the Optional type, i.e. a short hand for Variant[T, Undef]
# If the given 'optional_type' argument is a String, then it will be
# converted into a String type that represents that string.
#
# @param optional_type [String,PAnyType,nil] the optional type
# @return [POptionalType] the created type
#
# @api public
#
def self.optional(optional_type = nil)
if optional_type.nil?
POptionalType::DEFAULT
else
POptionalType.new(type_of(optional_type.is_a?(String) ? string(optional_type) : type_of(optional_type)))
end
end
# Produces the Enum type, optionally with specific string values
# @api public
#
def self.enum(*values)
last = values.last
case_insensitive = false
if last == true || last == false
case_insensitive = last
values = values[0...-1]
end
PEnumType.new(values, case_insensitive)
end
# Produces the Variant type, optionally with the "one of" types
# @api public
#
def self.variant(*types)
PVariantType.maybe_create(types.map { |v| type_of(v) })
end
# Produces the Struct type, either a non parameterized instance representing
# all structs (i.e. all hashes) or a hash with entries where the key is
# either a literal String, an Enum with one entry, or a String representing exactly one value.
# The key type may also be wrapped in a NotUndef or an Optional.
#
# The value can be a ruby class, a String (interpreted as the name of a ruby class) or
# a Type.
#
# @param hash [{String,PAnyType=>PAnyType}] key => value hash
# @return [PStructType] the created Struct type
#
def self.struct(hash = {})
tc = @type_calculator
elements = hash.map do |key_type, value_type|
value_type = type_of(value_type)
raise ArgumentError, 'Struct element value_type must be a Type' unless value_type.is_a?(PAnyType)
# TODO: Should have stricter name rule
if key_type.is_a?(String)
raise ArgumentError, 'Struct element key cannot be an empty String' if key_type.empty?
key_type = string(key_type)
# Must make key optional if the value can be Undef
key_type = optional(key_type) if tc.assignable?(value_type, PUndefType::DEFAULT)
else
# assert that the key type is one of String[1], NotUndef[String[1]] and Optional[String[1]]
case key_type
when PNotUndefType
# We can loose the NotUndef wrapper here since String[1] isn't optional anyway
key_type = key_type.type
s = key_type
when POptionalType
s = key_type.optional_type
when PStringType
s = key_type
when PEnumType
s = key_type.values.size == 1 ? PStringType.new(key_type.values[0]) : nil
else
raise ArgumentError, "Illegal Struct member key type. Expected NotUndef, Optional, String, or Enum. Got: #{key_type.class.name}"
end
unless s.is_a?(PStringType) && !s.value.nil?
raise ArgumentError, "Unable to extract a non-empty literal string from Struct member key type #{tc.string(key_type)}"
end
end
PStructElement.new(key_type, value_type)
end
PStructType.new(elements)
end
# Produces an `Object` type from the given _hash_ that represents the features of the object
#
# @param hash [{String=>Object}] the hash of feature groups
# @return [PObjectType] the created type
#
def self.object(hash = nil, loader = nil)
hash.nil? || hash.empty? ? PObjectType::DEFAULT : PObjectType.new(hash, loader)
end
def self.type_set(hash = nil)
hash.nil? || hash.empty? ? PTypeSetType::DEFAULT : PTypeSetType.new(hash)
end
def self.timestamp(*args)
case args.size
when 0
PTimestampType::DEFAULT
else
PTimestampType.new(*args)
end
end
def self.timespan(*args)
case args.size
when 0
PTimespanType::DEFAULT
else
PTimespanType.new(*args)
end
end
def self.tuple(types = [], size_type = nil)
PTupleType.new(types.map { |elem| type_of(elem) }, size_type)
end
# Produces the Boolean type
# @api public
#
def self.boolean(value = nil)
if value.nil?
PBooleanType::DEFAULT
else
value ? PBooleanType::TRUE : PBooleanType::FALSE
end
end
# Produces the Any type
# @api public
#
def self.any
PAnyType::DEFAULT
end
# Produces the Regexp type
# @param pattern [Regexp, String, nil] (nil) The regular expression object or
# a regexp source string, or nil for bare type
# @api public
#
def self.regexp(pattern = nil)
pattern ? PRegexpType.new(pattern) : PRegexpType::DEFAULT
end
def self.pattern(*regular_expressions)
patterns = regular_expressions.map do |re|
case re
when String
re_t = PRegexpType.new(re)
re_t.regexp # compile it to catch errors
re_t
when Regexp
PRegexpType.new(re)
when PRegexpType
re
when PPatternType
re.patterns
else
raise ArgumentError, "Only String, Regexp, Pattern-Type, and Regexp-Type are allowed: got '#{re.class}"
end
end.flatten.uniq
PPatternType.new(patterns)
end
# Produces the Scalar type
# @api public
#
def self.scalar
PScalarType::DEFAULT
end
# Produces the ScalarData type
# @api public
#
def self.scalar_data
PScalarDataType::DEFAULT
end
# Produces a CallableType matching all callables
# @api public
#
def self.all_callables
PCallableType::DEFAULT
end
# Produces a Callable type with one signature without support for a block
# Use #with_block, or #with_optional_block to add a block to the callable
# If no parameters are given, the Callable will describe a signature
# that does not accept parameters. To create a Callable that matches all callables
# use {#all_callables}.
#
# The params is a list of types, where the three last entries may be
# optionally followed by min, max count, and a Callable which is taken as the
# block_type.
# If neither min or max are specified the parameters must match exactly.
# A min < params.size means that the difference are optional.
# If max > params.size means that the last type repeats.
# if max is :default, the max value is unbound (infinity).
#
# Params are given as a sequence of arguments to {#type_of}.
#
def self.callable(*params)
if params.size == 2 && params[0].is_a?(Array)
return_t = type_of(params[1])
params = params[0]
else
return_t = nil
end
last_callable = TypeCalculator.is_kind_of_callable?(params.last)
block_t = last_callable ? params.pop : nil
# compute a size_type for the signature based on the two last parameters
if is_range_parameter?(params[-2]) && is_range_parameter?(params[-1])
size_type = range(params[-2], params[-1])
params = params[0, params.size - 2]
elsif is_range_parameter?(params[-1])
size_type = range(params[-1], :default)
params = params[0, params.size - 1]
else
size_type = nil
end
types = params.map { |p| type_of(p) }
# If the specification requires types, and none were given, a Unit type is used
if types.empty? && !size_type.nil? && size_type.range[1] > 0
types << PUnitType::DEFAULT
end
# create a signature
tuple_t = tuple(types, size_type)
PCallableType.new(tuple_t, block_t, return_t)
end
# Produces the abstract type Collection
# @api public
#
def self.collection(size_type = nil)
size_type.nil? ? PCollectionType::DEFAULT : PCollectionType.new(size_type)
end
# Produces the Data type
# @api public
#
def self.data
@data_t ||= TypeParser.singleton.parse('Data', Loaders.static_loader)
end
# Produces the RichData type
# @api public
#
def self.rich_data
@rich_data_t ||= TypeParser.singleton.parse('RichData', Loaders.static_loader)
end
# Produces the RichData type
# @api public
#
def self.rich_data_key
@rich_data_key_t ||= TypeParser.singleton.parse('RichDataKey', Loaders.static_loader)
end
# Creates an instance of the Undef type
# @api public
def self.undef
PUndefType::DEFAULT
end
# Creates an instance of the Default type
# @api public
def self.default
PDefaultType::DEFAULT
end
# Creates an instance of the Binary type
# @api public
def self.binary
PBinaryType::DEFAULT
end
# Produces an instance of the abstract type PCatalogEntryType
def self.catalog_entry
PCatalogEntryType::DEFAULT
end
# Produces an instance of the SemVerRange type
def self.sem_ver_range
PSemVerRangeType::DEFAULT
end
# Produces an instance of the SemVer type
def self.sem_ver(*ranges)
ranges.empty? ? PSemVerType::DEFAULT : PSemVerType.new(ranges)
end
# Produces a PResourceType with a String type_name A PResourceType with a nil
# or empty name is compatible with any other PResourceType. A PResourceType
# with a given name is only compatible with a PResourceType with the same
# name. (There is no resource-type subtyping in Puppet (yet)).
#
def self.resource(type_name = nil, title = nil)
case type_name
when PResourceType
PResourceType.new(type_name.type_name, title)
when String
type_name = TypeFormatter.singleton.capitalize_segments(type_name)
raise ArgumentError, "Illegal type name '#{type_name}'" unless type_name =~ Patterns::CLASSREF_EXT
PResourceType.new(type_name, title)
when nil
raise ArgumentError, 'The type name cannot be nil, if title is given' unless title.nil?
PResourceType::DEFAULT
else
raise ArgumentError, "The type name cannot be a #{type_name.class.name}"
end
end
# Produces PClassType with a string class_name. A PClassType with
# nil or empty name is compatible with any other PClassType. A
# PClassType with a given name is only compatible with a PClassType
# with the same name.
#
def self.host_class(class_name = nil)
if class_name.nil?
PClassType::DEFAULT
else
PClassType.new(class_name.sub(/^::/, ''))
end
end
# Produces a type for Array[o] where o is either a type, or an instance for
# which a type is inferred.
# @api public
#
def self.array_of(o, size_type = nil)
PArrayType.new(type_of(o), size_type)
end
# Produces a type for Hash[Scalar, o] where o is either a type, or an
# instance for which a type is inferred.
# @api public
#
def self.hash_of(value, key = scalar, size_type = nil)
PHashType.new(type_of(key), type_of(value), size_type)
end
# Produces a type for Hash[key,value,size]
# @param key_type [PAnyType] the key type
# @param value_type [PAnyType] the value type
# @param size_type [PIntegerType]
# @return [PHashType] the created hash type
# @api public
#
def self.hash_kv(key_type, value_type, size_type = nil)
PHashType.new(key_type, value_type, size_type)
end
# Produces a type for Array[Any]
# @api public
#
def self.array_of_any
PArrayType::DEFAULT
end
# Produces a type for Array[Data]
# @api public
#
def self.array_of_data
@array_of_data_t = PArrayType.new(data)
end
# Produces a type for Hash[Any,Any]
# @api public
#
def self.hash_of_any
PHashType::DEFAULT
end
# Produces a type for Hash[String,Data]
# @api public
#
def self.hash_of_data
@hash_of_data_t = PHashType.new(string, data)
end
# Produces a type for NotUndef[T]
# The given 'inst_type' can be a string in which case it will be converted into
# the type String[inst_type].
#
# @param inst_type [Type,String] the type to qualify
# @return [PNotUndefType] the NotUndef type
#
# @api public
#
def self.not_undef(inst_type = nil)
inst_type = string(inst_type) if inst_type.is_a?(String)
PNotUndefType.new(inst_type)
end
# Produces a type for Type[T]
# @api public
#
def self.type_type(inst_type = nil)
inst_type.nil? ? PTypeType::DEFAULT : PTypeType.new(inst_type)
end
# Produces a type for Error
# @api public
#
def self.error
@error_t ||= TypeParser.singleton.parse('Error', Loaders.loaders.puppet_system_loader)
end
def self.task
@task_t ||= TypeParser.singleton.parse('Task')
end
def self.deferred
@deferred_t ||= TypeParser.singleton.parse('Deferred')
end
# Produces a type for URI[String or Hash]
# @api public
#
def self.uri(string_uri_or_hash = nil)
string_uri_or_hash.nil? ? PURIType::DEFAULT : PURIType.new(string_uri_or_hash)
end
# Produce a type corresponding to the class of given unless given is a
# String, Class or a PAnyType. When a String is given this is taken as
# a classname.
#
def self.type_of(o)
case o
when Class
@type_calculator.type(o)
when PAnyType
o
when String
PRuntimeType.new(:ruby, o)
else
@type_calculator.infer_generic(o)
end
end
# Produces a type for a class or infers a type for something that is not a
# class
# @note
# To get the type for the class' class use `TypeCalculator.infer(c)`
#
# @overload ruby(o)
# @param o [Class] produces the type corresponding to the class (e.g.
# Integer becomes PIntegerType)
# @overload ruby(o)
# @param o [Object] produces the type corresponding to the instance class
# (e.g. 3 becomes PIntegerType)
#
# @api public
#
def self.ruby(o)
if o.is_a?(Class)
@type_calculator.type(o)
else
PRuntimeType.new(:ruby, o.class.name)
end
end
# Generic creator of a RuntimeType["ruby"] - allows creating the Ruby type
# with nil name, or String name. Also see ruby(o) which performs inference,
# or mapps a Ruby Class to its name.
#
def self.ruby_type(class_name = nil)
PRuntimeType.new(:ruby, class_name)
end
# Generic creator of a RuntimeType - allows creating the type with nil or
# String runtime_type_name. Also see ruby_type(o) and ruby(o).
#
def self.runtime(runtime = nil, runtime_type_name = nil)
runtime = runtime.to_sym if runtime.is_a?(String)
PRuntimeType.new(runtime, runtime_type_name)
end
# Returns the type alias for the given expression
# @param name [String] the name of the unresolved type
# @param expression [Model::Expression] an expression that will evaluate to a type
# @return [PTypeAliasType] the type alias
def self.type_alias(name = nil, expression = nil)
name.nil? ? PTypeAliasType::DEFAULT : PTypeAliasType.new(name, expression)
end
# Returns the type that represents a type reference with a given name and optional
# parameters.
# @param type_string [String] the string form of the type
# @return [PTypeReferenceType] the type reference
def self.type_reference(type_string = nil)
type_string.nil? ? PTypeReferenceType::DEFAULT : PTypeReferenceType.new(type_string)
end
# Returns true if the given type t is of valid range parameter type (integer
# or literal default).
def self.is_range_parameter?(t)
t.is_a?(Integer) || t == 'default' || :default == t
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/p_meta_type.rb | lib/puppet/pops/types/p_meta_type.rb | # frozen_string_literal: true
# @abstract base class for PObjectType and other types that implements lazy evaluation of content
# @api private
module Puppet::Pops
module Types
KEY_NAME = 'name'
KEY_TYPE = 'type'
KEY_VALUE = 'value'
class PMetaType < PAnyType
include Annotatable
attr_reader :loader
def self.register_ptype(loader, ir)
# Abstract type. It doesn't register anything
end
def accept(visitor, guard)
annotatable_accept(visitor, guard)
super
end
def instance?(o, guard = nil)
raise NotImplementedError, "Subclass of PMetaType should implement 'instance?'"
end
# Called from the TypeParser once it has found a type using the Loader. The TypeParser will
# interpret the contained expression and the resolved type is remembered. This method also
# checks and remembers if the resolve type contains self recursion.
#
# @param type_parser [TypeParser] type parser that will interpret the type expression
# @param loader [Loader::Loader] loader to use when loading type aliases
# @return [PTypeAliasType] the receiver of the call, i.e. `self`
# @api private
def resolve(loader)
unless @init_hash_expression.nil?
@loader = loader
@self_recursion = true # assumed while it being found out below
init_hash_expression = @init_hash_expression
@init_hash_expression = nil
if init_hash_expression.is_a?(Model::LiteralHash)
init_hash = resolve_literal_hash(loader, init_hash_expression)
else
init_hash = resolve_hash(loader, init_hash_expression)
end
_pcore_init_from_hash(init_hash)
# Find out if this type is recursive. A recursive type has performance implications
# on several methods and this knowledge is used to avoid that for non-recursive
# types.
guard = RecursionGuard.new
accept(NoopTypeAcceptor::INSTANCE, guard)
@self_recursion = guard.recursive_this?(self)
end
self
end
def resolve_literal_hash(loader, init_hash_expression)
TypeParser.singleton.interpret_LiteralHash(init_hash_expression, loader)
end
def resolve_hash(loader, init_hash)
resolve_type_refs(loader, init_hash)
end
def resolve_type_refs(loader, o)
case o
when Hash
o.to_h { |k, v| [resolve_type_refs(loader, k), resolve_type_refs(loader, v)] }
when Array
o.map { |e| resolve_type_refs(loader, e) }
when PAnyType
o.resolve(loader)
else
o
end
end
def resolved?
@init_hash_expression.nil?
end
# Returns the expanded string the form of the alias, e.g. <alias name> = <resolved type>
#
# @return [String] the expanded form of this alias
# @api public
def to_s
TypeFormatter.singleton.alias_expanded_string(self)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/ruby_generator.rb | lib/puppet/pops/types/ruby_generator.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
# @api private
class RubyGenerator < TypeFormatter
RUBY_RESERVED_WORDS = {
'alias' => '_alias',
'begin' => '_begin',
'break' => '_break',
'def' => '_def',
'do' => '_do',
'end' => '_end',
'ensure' => '_ensure',
'for' => '_for',
'module' => '_module',
'next' => '_next',
'nil' => '_nil',
'not' => '_not',
'redo' => '_redo',
'rescue' => '_rescue',
'retry' => '_retry',
'return' => '_return',
'self' => '_self',
'super' => '_super',
'then' => '_then',
'until' => '_until',
'when' => '_when',
'while' => '_while',
'yield' => '_yield',
}
RUBY_RESERVED_WORDS_REVERSED = RUBY_RESERVED_WORDS.to_h { |k, v| [v, k] }
def self.protect_reserved_name(name)
RUBY_RESERVED_WORDS[name] || name
end
def self.unprotect_reserved_name(name)
RUBY_RESERVED_WORDS_REVERSED[name] || name
end
def remove_common_namespace(namespace_segments, name)
segments = name.split(TypeFormatter::NAME_SEGMENT_SEPARATOR)
namespace_segments.size.times do |idx|
break if segments.empty? || namespace_segments[idx] != segments[0]
segments.shift
end
segments
end
def namespace_relative(namespace_segments, name)
remove_common_namespace(namespace_segments, name).join(TypeFormatter::NAME_SEGMENT_SEPARATOR)
end
def create_class(obj)
@dynamic_classes ||= Hash.new do |hash, key|
cls = key.implementation_class(false)
if cls.nil?
rp = key.resolved_parent
parent_class = rp.is_a?(PObjectType) ? rp.implementation_class : Object
class_def = ''.dup
class_body(key, EMPTY_ARRAY, class_def)
cls = Class.new(parent_class)
cls.class_eval(class_def)
cls.define_singleton_method(:_pcore_type) { key }
key.implementation_class = cls
end
hash[key] = cls
end
raise ArgumentError, "Expected a Puppet Type, got '#{obj.class.name}'" unless obj.is_a?(PAnyType)
@dynamic_classes[obj]
end
def module_definition_from_typeset(typeset, *impl_subst)
module_definition(
typeset.types.values,
"# Generated by #{self.class.name} from TypeSet #{typeset.name} on #{Date.new}\n",
*impl_subst
)
end
def module_definition(types, comment, *impl_subst)
object_types, aliased_types = types.partition { |type| type.is_a?(PObjectType) }
if impl_subst.empty?
impl_names = implementation_names(object_types)
else
impl_names = object_types.map { |type| type.name.gsub(*impl_subst) }
end
# extract common implementation module prefix
names_by_prefix = Hash.new { |hash, key| hash[key] = [] }
index = 0
min_prefix_length = impl_names.reduce(Float::INFINITY) do |len, impl_name|
segments = impl_name.split(TypeFormatter::NAME_SEGMENT_SEPARATOR)
leaf_name = segments.pop
names_by_prefix[segments.freeze] << [index, leaf_name, impl_name]
index += 1
len > segments.size ? segments.size : len
end
min_prefix_length = 0 if min_prefix_length == Float::INFINITY
common_prefix = []
segments_array = names_by_prefix.keys
min_prefix_length.times do |idx|
segment = segments_array[0][idx]
break unless segments_array.all? { |sn| sn[idx] == segment }
common_prefix << segment
end
# Create class definition of all contained types
bld = ''.dup
start_module(common_prefix, comment, bld)
class_names = []
names_by_prefix.each_pair do |seg_array, index_and_name_array|
added_to_common_prefix = seg_array[common_prefix.length..]
added_to_common_prefix.each { |name| bld << 'module ' << name << "\n" }
index_and_name_array.each do |idx, name, full_name|
scoped_class_definition(object_types[idx], name, bld, full_name, *impl_subst)
class_names << (added_to_common_prefix + [name]).join(TypeFormatter::NAME_SEGMENT_SEPARATOR)
bld << "\n"
end
added_to_common_prefix.size.times { bld << "end\n" }
end
aliases = aliased_types.to_h { |type| [type.name, type.resolved_type] }
end_module(common_prefix, aliases, class_names, bld)
bld
end
def start_module(common_prefix, comment, bld)
bld << '# ' << comment << "\n"
common_prefix.each { |cp| bld << 'module ' << cp << "\n" }
end
def end_module(common_prefix, aliases, class_names, bld)
# Emit registration of contained type aliases
unless aliases.empty?
bld << "Puppet::Pops::Pcore.register_aliases({\n"
aliases.each { |name, type| bld << " '" << name << "' => " << TypeFormatter.string(type.to_s) << "\n" }
bld.chomp!(",\n")
bld << "})\n\n"
end
# Emit registration of contained types
unless class_names.empty?
bld << "Puppet::Pops::Pcore.register_implementations([\n"
class_names.each { |class_name| bld << ' ' << class_name << ",\n" }
bld.chomp!(",\n")
bld << "])\n\n"
end
bld.chomp!("\n")
common_prefix.size.times { bld << "end\n" }
end
def implementation_names(object_types)
object_types.map do |type|
ir = Loaders.implementation_registry
impl_name = ir.module_name_for_type(type)
raise Puppet::Error, "Unable to create an instance of #{type.name}. No mapping exists to runtime object" if impl_name.nil?
impl_name
end
end
def class_definition(obj, namespace_segments, bld, class_name, *impl_subst)
module_segments = remove_common_namespace(namespace_segments, class_name)
leaf_name = module_segments.pop
module_segments.each { |segment| bld << 'module ' << segment << "\n" }
scoped_class_definition(obj, leaf_name, bld, class_name, *impl_subst)
module_segments.size.times { bld << "end\n" }
module_segments << leaf_name
module_segments.join(TypeFormatter::NAME_SEGMENT_SEPARATOR)
end
def scoped_class_definition(obj, leaf_name, bld, class_name, *impl_subst)
bld << 'class ' << leaf_name
segments = class_name.split(TypeFormatter::NAME_SEGMENT_SEPARATOR)
unless obj.parent.nil?
if impl_subst.empty?
ir = Loaders.implementation_registry
parent_name = ir.module_name_for_type(obj.parent)
raise Puppet::Error, "Unable to create an instance of #{obj.parent.name}. No mapping exists to runtime object" if parent_name.nil?
else
parent_name = obj.parent.name.gsub(*impl_subst)
end
bld << ' < ' << namespace_relative(segments, parent_name)
end
bld << "\n"
bld << " def self._pcore_type\n"
bld << ' @_pcore_type ||= ' << namespace_relative(segments, obj.class.name) << ".new('" << obj.name << "', "
bld << TypeFormatter.singleton.ruby('ref').indented(2).string(obj._pcore_init_hash(false)) << ")\n"
bld << " end\n"
class_body(obj, segments, bld)
bld << "end\n"
end
def class_body(obj, segments, bld)
unless obj.parent.is_a?(PObjectType)
bld << "\n include " << namespace_relative(segments, Puppet::Pops::Types::PuppetObject.name) << "\n\n" # marker interface
bld << " def self.ref(type_string)\n"
bld << ' ' << namespace_relative(segments, Puppet::Pops::Types::PTypeReferenceType.name) << ".new(type_string)\n"
bld << " end\n"
end
# Output constants
constants, others = obj.attributes(true).values.partition { |a| a.kind == PObjectType::ATTRIBUTE_KIND_CONSTANT }
constants = constants.select { |ca| ca.container.equal?(obj) }
unless constants.empty?
constants.each { |ca| bld << "\n def self." << rname(ca.name) << "\n _pcore_type['" << ca.name << "'].value\n end\n" }
constants.each { |ca| bld << "\n def " << rname(ca.name) << "\n self.class." << ca.name << "\n end\n" }
end
init_params = others.reject { |a| a.kind == PObjectType::ATTRIBUTE_KIND_DERIVED }
opt, non_opt = init_params.partition(&:value?)
derived_attrs, obj_attrs = others.select { |a| a.container.equal?(obj) }.partition { |ip| ip.kind == PObjectType::ATTRIBUTE_KIND_DERIVED }
include_type = obj.equality_include_type? && !(obj.parent.is_a?(PObjectType) && obj.parent.equality_include_type?)
if obj.equality.nil?
eq_names = obj_attrs.reject { |a| a.kind == PObjectType::ATTRIBUTE_KIND_CONSTANT }.map(&:name)
else
eq_names = obj.equality
end
# Output type safe hash constructor
bld << "\n def self.from_hash(init_hash)\n"
bld << ' from_asserted_hash(' << namespace_relative(segments, TypeAsserter.name) << '.assert_instance_of('
bld << "'" << obj.label << " initializer', _pcore_type.init_hash_type, init_hash))\n end\n\n def self.from_asserted_hash(init_hash)\n new"
unless non_opt.empty? && opt.empty?
bld << "(\n"
non_opt.each { |ip| bld << " init_hash['" << ip.name << "'],\n" }
opt.each do |ip|
if ip.value.nil?
bld << " init_hash['" << ip.name << "'],\n"
else
bld << " init_hash.fetch('" << ip.name << "') { "
default_string(bld, ip)
bld << " },\n"
end
end
bld.chomp!(",\n")
bld << ')'
end
bld << "\n end\n"
# Output type safe constructor
bld << "\n def self.create"
if init_params.empty?
bld << "\n new"
else
bld << '('
non_opt.each { |ip| bld << rname(ip.name) << ', ' }
opt.each do |ip|
bld << rname(ip.name) << ' = '
default_string(bld, ip)
bld << ', '
end
bld.chomp!(', ')
bld << ")\n"
bld << ' ta = ' << namespace_relative(segments, TypeAsserter.name) << "\n"
bld << " attrs = _pcore_type.attributes(true)\n"
init_params.each do |a|
bld << " ta.assert_instance_of('" << a.container.name << '[' << a.name << ']'
bld << "', attrs['" << a.name << "'].type, " << rname(a.name) << ")\n"
end
bld << ' new('
non_opt.each { |a| bld << rname(a.name) << ', ' }
opt.each { |a| bld << rname(a.name) << ', ' }
bld.chomp!(', ')
bld << ')'
end
bld << "\n end\n"
unless obj.parent.is_a?(PObjectType) && obj_attrs.empty?
# Output attr_readers
unless obj_attrs.empty?
bld << "\n"
obj_attrs.each { |a| bld << ' attr_reader :' << rname(a.name) << "\n" }
end
bld << " attr_reader :hash\n" if obj.parent.nil?
derived_attrs.each do |a|
bld << "\n def " << rname(a.name) << "\n"
code_annotation = RubyMethod.annotate(a)
ruby_body = code_annotation.nil? ? nil : code_annotation.body
if ruby_body.nil?
bld << " raise Puppet::Error, \"no method is implemented for derived #{a.label}\"\n"
else
bld << ' ' << ruby_body << "\n"
end
bld << " end\n"
end
if init_params.empty?
bld << "\n def initialize\n @hash = " << obj.hash.to_s << "\n end" if obj.parent.nil?
else
# Output initializer
bld << "\n def initialize"
bld << '('
non_opt.each { |ip| bld << rname(ip.name) << ', ' }
opt.each do |ip|
bld << rname(ip.name) << ' = '
default_string(bld, ip)
bld << ', '
end
bld.chomp!(', ')
bld << ')'
hash_participants = init_params.select { |ip| eq_names.include?(ip.name) }
if obj.parent.nil?
bld << "\n @hash = "
bld << obj.hash.to_s << "\n" if hash_participants.empty?
else
bld << "\n super("
super_args = (non_opt + opt).select { |ip| !ip.container.equal?(obj) }
unless super_args.empty?
super_args.each { |ip| bld << rname(ip.name) << ', ' }
bld.chomp!(', ')
end
bld << ")\n"
bld << ' @hash = @hash ^ ' unless hash_participants.empty?
end
unless hash_participants.empty?
hash_participants.each { |a| bld << rname(a.name) << '.hash ^ ' if a.container.equal?(obj) }
bld.chomp!(' ^ ')
bld << "\n"
end
init_params.each { |a| bld << ' @' << rname(a.name) << ' = ' << rname(a.name) << "\n" if a.container.equal?(obj) }
bld << " end\n"
end
end
unless obj_attrs.empty? && obj.parent.nil?
bld << "\n def _pcore_init_hash\n"
bld << ' result = '
bld << (obj.parent.nil? ? '{}' : 'super')
bld << "\n"
obj_attrs.each do |a|
bld << " result['" << a.name << "'] = @" << rname(a.name)
if a.value?
bld << ' unless '
equals_default_string(bld, a)
end
bld << "\n"
end
bld << " result\n end\n"
end
content_participants = init_params.select { |a| content_participant?(a) }
if content_participants.empty?
unless obj.parent.is_a?(PObjectType)
bld << "\n def _pcore_contents\n end\n"
bld << "\n def _pcore_all_contents(path)\n end\n"
end
else
bld << "\n def _pcore_contents\n"
content_participants.each do |cp|
if array_type?(cp.type)
bld << ' @' << rname(cp.name) << ".each { |value| yield(value) }\n"
else
bld << ' yield(@' << rname(cp.name) << ') unless @' << rname(cp.name) << ".nil?\n"
end
end
bld << " end\n\n def _pcore_all_contents(path, &block)\n path << self\n"
content_participants.each do |cp|
if array_type?(cp.type)
bld << ' @' << rname(cp.name) << ".each do |value|\n"
bld << " block.call(value, path)\n"
bld << " value._pcore_all_contents(path, &block)\n"
else
bld << ' unless @' << rname(cp.name) << ".nil?\n"
bld << ' block.call(@' << rname(cp.name) << ", path)\n"
bld << ' @' << rname(cp.name) << "._pcore_all_contents(path, &block)\n"
end
bld << " end\n"
end
bld << " path.pop\n end\n"
end
# Output function placeholders
obj.functions(false).each_value do |func|
code_annotation = RubyMethod.annotate(func)
if code_annotation
body = code_annotation.body
params = code_annotation.parameters
bld << "\n def " << rname(func.name)
unless params.nil? || params.empty?
bld << '(' << params << ')'
end
bld << "\n " << body << "\n"
else
bld << "\n def " << rname(func.name) << "(*args)\n"
bld << " # Placeholder for #{func.type}\n"
bld << " raise Puppet::Error, \"no method is implemented for #{func.label}\"\n"
end
bld << " end\n"
end
unless eq_names.empty? && !include_type
bld << "\n def eql?(o)\n"
bld << " super &&\n" unless obj.parent.nil?
bld << " o.instance_of?(self.class) &&\n" if include_type
eq_names.each { |eqn| bld << ' @' << rname(eqn) << '.eql?(o.' << rname(eqn) << ") &&\n" }
bld.chomp!(" &&\n")
bld << "\n end\n alias == eql?\n"
end
end
def content_participant?(a)
a.kind != PObjectType::ATTRIBUTE_KIND_REFERENCE && obj_type?(a.type)
end
def obj_type?(t)
case t
when PObjectType
true
when POptionalType
obj_type?(t.optional_type)
when PNotUndefType
obj_type?(t.type)
when PArrayType
obj_type?(t.element_type)
when PVariantType
t.types.all? { |v| obj_type?(v) }
else
false
end
end
def array_type?(t)
case t
when PArrayType
true
when POptionalType
array_type?(t.optional_type)
when PNotUndefType
array_type?(t.type)
when PVariantType
t.types.all? { |v| array_type?(v) }
else
false
end
end
def default_string(bld, a)
case a.value
when nil, true, false, Numeric, String
bld << a.value.inspect
else
bld << "_pcore_type['" << a.name << "'].value"
end
end
def equals_default_string(bld, a)
case a.value
when nil, true, false, Numeric, String
bld << '@' << a.name << ' == ' << a.value.inspect
else
bld << "_pcore_type['" << a.name << "'].default_value?(@" << a.name << ')'
end
end
def rname(name)
RUBY_RESERVED_WORDS[name] || name
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/ruby_method.rb | lib/puppet/pops/types/ruby_method.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
class RubyMethod < Annotation
# Register the Annotation type. This is the type that all custom Annotations will inherit from.
def self.register_ptype(loader, ir)
@type = Pcore.create_object_type(loader, ir, self, 'RubyMethod', 'Annotation',
'body' => PStringType::DEFAULT,
'parameters' => {
KEY_TYPE => POptionalType.new(PStringType::NON_EMPTY),
KEY_VALUE => nil
})
end
def self.from_hash(init_hash)
from_asserted_hash(Types::TypeAsserter.assert_instance_of('RubyMethod initializer', _pcore_type.init_hash_type, init_hash))
end
def self.from_asserted_hash(init_hash)
new(init_hash['body'], init_hash['parameters'])
end
attr_reader :body, :parameters
def initialize(body, parameters = nil)
@body = body
@parameters = parameters
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/p_sem_ver_type.rb | lib/puppet/pops/types/p_sem_ver_type.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
# A Puppet Language Type that exposes the {{SemanticPuppet::Version}} and {{SemanticPuppet::VersionRange}}.
# The version type is parameterized with version ranges.
#
# @api public
class PSemVerType < PScalarType
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'ScalarType',
'ranges' => {
KEY_TYPE => PArrayType.new(PVariantType.new([PSemVerRangeType::DEFAULT, PStringType::NON_EMPTY])),
KEY_VALUE => []
})
end
attr_reader :ranges
def initialize(ranges)
ranges = ranges.map { |range| range.is_a?(SemanticPuppet::VersionRange) ? range : SemanticPuppet::VersionRange.parse(range) }
ranges = merge_ranges(ranges) if ranges.size > 1
@ranges = ranges
end
def instance?(o, guard = nil)
o.is_a?(SemanticPuppet::Version) && (@ranges.empty? || @ranges.any? { |range| range.include?(o) })
end
def eql?(o)
self.class == o.class && @ranges == o.ranges
end
def hash?
super ^ @ranges.hash
end
# Creates a SemVer version from the given _version_ argument. If the argument is `nil` or
# a {SemanticPuppet::Version}, it is returned. If it is a {String}, it will be parsed into a
# {SemanticPuppet::Version}. Any other class will raise an {ArgumentError}.
#
# @param version [SemanticPuppet::Version,String,nil] the version to convert
# @return [SemanticPuppet::Version] the converted version
# @raise [ArgumentError] when the argument cannot be converted into a version
#
def self.convert(version)
case version
when nil, SemanticPuppet::Version
version
when String
SemanticPuppet::Version.parse(version)
else
raise ArgumentError, "Unable to convert a #{version.class.name} to a SemVer"
end
end
# @api private
def self.new_function(type)
@new_function ||= Puppet::Functions.create_loaded_function(:new_Version, type.loader) do
local_types do
type 'PositiveInteger = Integer[0,default]'
type 'SemVerQualifier = Pattern[/\A(?<part>[0-9A-Za-z-]+)(?:\.\g<part>)*\Z/]'
type "SemVerPattern = Pattern[/\\A#{SemanticPuppet::Version::REGEX_FULL}\\Z/]"
type 'SemVerHash = Struct[{major=>PositiveInteger,minor=>PositiveInteger,patch=>PositiveInteger,Optional[prerelease]=>SemVerQualifier,Optional[build]=>SemVerQualifier}]'
end
# Creates a SemVer from a string as specified by http://semver.org/
#
dispatch :from_string do
param 'SemVerPattern', :str
end
# Creates a SemVer from integers, prerelease, and build arguments
#
dispatch :from_args do
param 'PositiveInteger', :major
param 'PositiveInteger', :minor
param 'PositiveInteger', :patch
optional_param 'SemVerQualifier', :prerelease
optional_param 'SemVerQualifier', :build
end
# Same as #from_args but each argument is instead given in a Hash
#
dispatch :from_hash do
param 'SemVerHash', :hash_args
end
argument_mismatch :on_error do
param 'String', :str
end
def from_string(str)
SemanticPuppet::Version.parse(str)
end
def from_args(major, minor, patch, prerelease = nil, build = nil)
SemanticPuppet::Version.new(major, minor, patch, to_array(prerelease), to_array(build))
end
def from_hash(hash)
SemanticPuppet::Version.new(hash['major'], hash['minor'], hash['patch'], to_array(hash['prerelease']), to_array(hash['build']))
end
def on_error(str)
_("The string '%{str}' cannot be converted to a SemVer") % { str: str }
end
private
def to_array(component)
component ? [component] : nil
end
end
end
DEFAULT = PSemVerType.new(EMPTY_ARRAY)
protected
def _assignable?(o, guard)
return false unless o.instance_of?(self.class)
return true if @ranges.empty?
return false if o.ranges.empty?
# All ranges in o must be covered by at least one range in self
o.ranges.all? do |o_range|
@ranges.any? do |range|
PSemVerRangeType.covered_by?(o_range, range)
end
end
end
# @api private
def merge_ranges(ranges)
result = []
until ranges.empty?
unmerged = []
x = ranges.pop
result << ranges.inject(x) do |memo, y|
merged = PSemVerRangeType.merge(memo, y)
if merged.nil?
unmerged << y
else
memo = merged
end
memo
end
ranges = unmerged
end
result.reverse!
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/p_type_set_type.rb | lib/puppet/pops/types/p_type_set_type.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
KEY_NAME_AUTHORITY = 'name_authority'
KEY_TYPES = 'types'
KEY_ALIAS = 'alias'
KEY_VERSION = 'version'
KEY_VERSION_RANGE = 'version_range'
KEY_REFERENCES = 'references'
class PTypeSetType < PMetaType
# A Loader that makes the types known to the TypeSet visible
#
# @api private
class TypeSetLoader < Loader::BaseLoader
def initialize(type_set, parent)
super(parent, "(TypeSetFirstLoader '#{type_set.name}')", parent.environment)
@type_set = type_set
end
def name_authority
@type_set.name_authority
end
def model_loader
@type_set.loader
end
def find(typed_name)
if typed_name.type == :type && typed_name.name_authority == @type_set.name_authority
type = @type_set[typed_name.name]
return set_entry(typed_name, type) unless type.nil?
end
nil
end
end
TYPE_STRING_OR_VERSION = TypeFactory.variant(PStringType::NON_EMPTY, TypeFactory.sem_ver)
TYPE_STRING_OR_RANGE = TypeFactory.variant(PStringType::NON_EMPTY, TypeFactory.sem_ver_range)
TYPE_TYPE_REFERENCE_I12N =
TypeFactory
.struct({
KEY_NAME => Pcore::TYPE_QUALIFIED_REFERENCE,
KEY_VERSION_RANGE => TYPE_STRING_OR_RANGE,
TypeFactory.optional(KEY_NAME_AUTHORITY) => Pcore::TYPE_URI,
TypeFactory.optional(KEY_ANNOTATIONS) => TYPE_ANNOTATIONS
})
TYPE_TYPESET_I12N =
TypeFactory
.struct({
TypeFactory.optional(Pcore::KEY_PCORE_URI) => Pcore::TYPE_URI,
Pcore::KEY_PCORE_VERSION => TYPE_STRING_OR_VERSION,
TypeFactory.optional(KEY_NAME_AUTHORITY) => Pcore::TYPE_URI,
TypeFactory.optional(KEY_NAME) => Pcore::TYPE_QUALIFIED_REFERENCE,
TypeFactory.optional(KEY_VERSION) => TYPE_STRING_OR_VERSION,
TypeFactory.optional(KEY_TYPES) => TypeFactory.hash_kv(Pcore::TYPE_SIMPLE_TYPE_NAME, PVariantType.new([PTypeType::DEFAULT, PObjectType::TYPE_OBJECT_I12N]), PCollectionType::NOT_EMPTY_SIZE),
TypeFactory.optional(KEY_REFERENCES) => TypeFactory.hash_kv(Pcore::TYPE_SIMPLE_TYPE_NAME, TYPE_TYPE_REFERENCE_I12N, PCollectionType::NOT_EMPTY_SIZE),
TypeFactory.optional(KEY_ANNOTATIONS) => TYPE_ANNOTATIONS,
})
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'AnyType', '_pcore_init_hash' => TYPE_TYPESET_I12N.resolve(loader))
end
attr_reader :pcore_uri
attr_reader :pcore_version
attr_reader :name_authority
attr_reader :name
attr_reader :version
attr_reader :types
attr_reader :references
attr_reader :annotations
# Initialize a TypeSet Type instance. The initialization will use either a name and an initialization
# hash expression, or a fully resolved initialization hash.
#
# @overload initialize(name, init_hash_expression)
# Used when the TypeSet type is loaded using a type alias expression. When that happens, it is important that
# the actual resolution of the expression is deferred until all definitions have been made known to the current
# loader. The package will then be resolved when it is loaded by the {TypeParser}. "resolved" here, means that
# the hash expression is fully resolved, and then passed to the {#_pcore_init_from_hash} method.
# @param name [String] The name of the type set
# @param init_hash_expression [Model::LiteralHash] The hash describing the TypeSet features
# @param name_authority [String] The default name authority for the type set
#
# @overload initialize(init_hash)
# Used when the package is created by the {TypeFactory}. The init_hash must be fully resolved.
# @param init_hash [Hash{String=>Object}] The hash describing the TypeSet features
#
# @api private
def initialize(name_or_init_hash, init_hash_expression = nil, name_authority = nil)
@types = EMPTY_HASH
@references = EMPTY_HASH
if name_or_init_hash.is_a?(Hash)
_pcore_init_from_hash(name_or_init_hash)
else
# Creation using "type XXX = TypeSet[{}]". This means that the name is given
@name = TypeAsserter.assert_instance_of('TypeSet name', Pcore::TYPE_QUALIFIED_REFERENCE, name_or_init_hash)
@name_authority = TypeAsserter.assert_instance_of('TypeSet name_authority', Pcore::TYPE_URI, name_authority, true)
@init_hash_expression = init_hash_expression
end
end
# @api private
def _pcore_init_from_hash(init_hash)
TypeAsserter.assert_instance_of('TypeSet initializer', TYPE_TYPESET_I12N, init_hash)
# Name given to the loader have higher precedence than a name declared in the type
@name ||= init_hash[KEY_NAME].freeze
@name_authority ||= init_hash[KEY_NAME_AUTHORITY].freeze
@pcore_version = PSemVerType.convert(init_hash[Pcore::KEY_PCORE_VERSION]).freeze
unless Pcore::PARSABLE_PCORE_VERSIONS.include?(@pcore_version)
raise ArgumentError,
"The pcore version for TypeSet '#{@name}' is not understood by this runtime. Expected range #{Pcore::PARSABLE_PCORE_VERSIONS}, got #{@pcore_version}"
end
@pcore_uri = init_hash[Pcore::KEY_PCORE_URI].freeze
@version = PSemVerType.convert(init_hash[KEY_VERSION])
@types = init_hash[KEY_TYPES] || EMPTY_HASH
@types.freeze
# Map downcase names to their camel-cased equivalent
@dc_to_cc_map = {}
@types.keys.each { |key| @dc_to_cc_map[key.downcase] = key }
refs = init_hash[KEY_REFERENCES]
if refs.nil?
@references = EMPTY_HASH
else
ref_map = {}
root_map = Hash.new { |h, k| h[k] = {} }
refs.each do |ref_alias, ref|
ref = TypeSetReference.new(self, ref)
# Protect against importing the exact same name_authority/name combination twice if the version ranges intersect
ref_name = ref.name
ref_na = ref.name_authority || @name_authority
na_roots = root_map[ref_na]
ranges = na_roots[ref_name]
if ranges.nil?
na_roots[ref_name] = [ref.version_range]
else
unless ranges.all? { |range| (range & ref.version_range).nil? }
raise ArgumentError, "TypeSet '#{@name}' references TypeSet '#{ref_na}/#{ref_name}' more than once using overlapping version ranges"
end
ranges << ref.version_range
end
if ref_map.has_key?(ref_alias)
raise ArgumentError, "TypeSet '#{@name}' references a TypeSet using alias '#{ref_alias}' more than once"
end
if @types.has_key?(ref_alias)
raise ArgumentError, "TypeSet '#{@name}' references a TypeSet using alias '#{ref_alias}'. The alias collides with the name of a declared type"
end
ref_map[ref_alias] = ref
@dc_to_cc_map[ref_alias.downcase] = ref_alias
ref_map[ref_alias] = ref
end
@references = ref_map.freeze
end
@dc_to_cc_map.freeze
init_annotatable(init_hash)
end
# Produce a hash suitable for the initializer
# @return [Hash{String => Object}] the initialization hash
#
# @api private
def _pcore_init_hash
result = super()
result[Pcore::KEY_PCORE_URI] = @pcore_uri unless @pcore_uri.nil?
result[Pcore::KEY_PCORE_VERSION] = @pcore_version.to_s
result[KEY_NAME_AUTHORITY] = @name_authority unless @name_authority.nil?
result[KEY_NAME] = @name
result[KEY_VERSION] = @version.to_s unless @version.nil?
result[KEY_TYPES] = @types unless @types.empty?
result[KEY_REFERENCES] = @references.transform_values(&:_pcore_init_hash) unless @references.empty?
result
end
# Resolve a type in this type set using a qualified name. The resolved type may either be a type defined in this type set
# or a type defined in a type set that is referenced by this type set (nesting may occur to any level).
# The name resolution is case insensitive.
#
# @param qname [String,Loader::TypedName] the qualified name of the type to resolve
# @return [PAnyType,nil] the resolved type, or `nil` in case no type could be found
#
# @api public
def [](qname)
if qname.is_a?(Loader::TypedName)
return nil unless qname.type == :type && qname.name_authority == @name_authority
qname = qname.name
end
type = @types[qname] || @types[@dc_to_cc_map[qname.downcase]]
if type.nil? && !@references.empty?
segments = qname.split(TypeFormatter::NAME_SEGMENT_SEPARATOR)
first = segments[0]
type_set_ref = @references[first] || @references[@dc_to_cc_map[first.downcase]]
if type_set_ref.nil?
nil
else
type_set = type_set_ref.type_set
case segments.size
when 1
type_set
when 2
type_set[segments[1]]
else
segments.shift
type_set[segments.join(TypeFormatter::NAME_SEGMENT_SEPARATOR)]
end
end
else
type
end
end
def defines_type?(t)
!@types.key(t).nil?
end
# Returns the name by which the given type is referenced from within this type set
# @param t [PAnyType]
# @return [String] the name by which the type is referenced within this type set
#
# @api private
def name_for(t, default_name)
key = @types.key(t)
if key.nil?
unless @references.empty?
@references.each_pair do |ref_key, ref|
ref_name = ref.type_set.name_for(t, nil)
return "#{ref_key}::#{ref_name}" unless ref_name.nil?
end
end
default_name
else
key
end
end
def accept(visitor, guard)
super
@types.each_value { |type| type.accept(visitor, guard) }
@references.each_value { |ref| ref.accept(visitor, guard) }
end
# @api private
def label
"TypeSet '#{@name}'"
end
# @api private
def resolve(loader)
super
@references.each_value { |ref| ref.resolve(loader) }
tsa_loader = TypeSetLoader.new(self, loader)
@types.values.each { |type| type.resolve(tsa_loader) }
self
end
# @api private
def resolve_literal_hash(loader, init_hash_expression)
result = {}
type_parser = TypeParser.singleton
init_hash_expression.entries.each do |entry|
key = type_parser.interpret_any(entry.key, loader)
if (key == KEY_TYPES || key == KEY_REFERENCES) && entry.value.is_a?(Model::LiteralHash)
# Skip type parser interpretation and convert qualified references directly to String keys.
hash = {}
entry.value.entries.each do |he|
kex = he.key
name = kex.is_a?(Model::QualifiedReference) ? kex.cased_value : type_parser.interpret_any(kex, loader)
hash[name] = key == KEY_TYPES ? he.value : type_parser.interpret_any(he.value, loader)
end
result[key] = hash
else
result[key] = type_parser.interpret_any(entry.value, loader)
end
end
name_auth = resolve_name_authority(result, loader)
types = result[KEY_TYPES]
if types.is_a?(Hash)
types.each do |type_name, value|
full_name = "#{@name}::#{type_name}"
typed_name = Loader::TypedName.new(:type, full_name, name_auth)
if value.is_a?(Model::ResourceDefaultsExpression)
# This is actually a <Parent> { <key-value entries> } notation. Convert to a literal hash that contains the parent
n = value.type_ref
name = n.cased_value
entries = []
unless name == 'Object' or name == 'TypeSet'
if value.operations.any? { |op| op.attribute_name == KEY_PARENT }
case Puppet[:strict]
when :warning
IssueReporter.warning(value, Issues::DUPLICATE_KEY, :key => KEY_PARENT)
when :error
IssueReporter.error(Puppet::ParseErrorWithIssue, value, Issues::DUPLICATE_KEY, :key => KEY_PARENT)
end
end
entries << Model::KeyedEntry.new(n.locator, n.offset, n.length, KEY_PARENT, n)
end
value.operations.each { |op| entries << Model::KeyedEntry.new(op.locator, op.offset, op.length, op.attribute_name, op.value_expr) }
value = Model::LiteralHash.new(value.locator, value.offset, value.length, entries)
end
type = Loader::TypeDefinitionInstantiator.create_type(full_name, value, name_auth)
loader.set_entry(typed_name, type, value.locator.to_uri(value))
types[type_name] = type
end
end
result
end
# @api private
def resolve_hash(loader, init_hash)
result = init_hash.to_h do |key, value|
key = resolve_type_refs(loader, key)
value = resolve_type_refs(loader, value) unless key == KEY_TYPES && value.is_a?(Hash)
[key, value]
end
name_auth = resolve_name_authority(result, loader)
types = result[KEY_TYPES]
if types.is_a?(Hash)
types.each do |type_name, value|
full_name = "#{@name}::#{type_name}"
typed_name = Loader::TypedName.new(:type, full_name, name_auth)
meta_name = value.is_a?(Hash) ? 'Object' : 'TypeAlias'
type = Loader::TypeDefinitionInstantiator.create_named_type(full_name, meta_name, value, name_auth)
loader.set_entry(typed_name, type)
types[type_name] = type
end
end
result
end
def hash
@name_authority.hash ^ @name.hash ^ @version.hash
end
def eql?(o)
self.class == o.class && @name_authority == o.name_authority && @name == o.name && @version == o.version
end
def instance?(o, guard = nil)
o.is_a?(PTypeSetType)
end
DEFAULT =
new({
KEY_NAME => 'DefaultTypeSet',
KEY_NAME_AUTHORITY => Pcore::RUNTIME_NAME_AUTHORITY,
Pcore::KEY_PCORE_URI => Pcore::PCORE_URI,
Pcore::KEY_PCORE_VERSION => Pcore::PCORE_VERSION,
KEY_VERSION => SemanticPuppet::Version.new(0, 0, 0)
})
protected
# @api_private
def _assignable?(o, guard)
instance_of?(o.class) && (self == DEFAULT || eql?(o))
end
private
def resolve_name_authority(init_hash, loader)
name_auth = @name_authority
if name_auth.nil?
name_auth = init_hash[KEY_NAME_AUTHORITY]
name_auth = loader.name_authority if name_auth.nil? && loader.is_a?(TypeSetLoader)
if name_auth.nil?
name = @name || init_hash[KEY_NAME]
raise ArgumentError, "No 'name_authority' is declared in TypeSet '#{name}' and it cannot be inferred"
end
end
name_auth
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/p_runtime_type.rb | lib/puppet/pops/types/p_runtime_type.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
# @api public
class PRuntimeType < PAnyType
TYPE_NAME_OR_PATTERN = PVariantType.new([PStringType::NON_EMPTY, PTupleType.new([PRegexpType::DEFAULT, PStringType::NON_EMPTY])])
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'AnyType',
'runtime' => {
KEY_TYPE => POptionalType.new(PStringType::NON_EMPTY),
KEY_VALUE => nil
},
'name_or_pattern' => {
KEY_TYPE => POptionalType.new(TYPE_NAME_OR_PATTERN),
KEY_VALUE => nil
})
end
attr_reader :runtime, :name_or_pattern
# Creates a new instance of a Runtime type
#
# @param runtime [String] the name of the runtime, e.g. 'ruby'
# @param name_or_pattern [String,Array(Regexp,String)] name of runtime or two patterns, mapping Puppet name => runtime name
# @api public
def initialize(runtime, name_or_pattern)
unless runtime.nil? || runtime.is_a?(Symbol)
runtime = TypeAsserter.assert_instance_of("Runtime 'runtime'", PStringType::NON_EMPTY, runtime).to_sym
end
@runtime = runtime
@name_or_pattern = TypeAsserter.assert_instance_of("Runtime 'name_or_pattern'", TYPE_NAME_OR_PATTERN, name_or_pattern, true)
end
def hash
@runtime.hash ^ @name_or_pattern.hash
end
def eql?(o)
self.class == o.class && @runtime == o.runtime && @name_or_pattern == o.name_or_pattern
end
def instance?(o, guard = nil)
assignable?(TypeCalculator.infer(o), guard)
end
def iterable?(guard = nil)
if @runtime == :ruby && !runtime_type_name.nil?
begin
c = ClassLoader.provide(self)
return c < Iterable unless c.nil?
rescue ArgumentError
end
end
false
end
def iterable_type(guard = nil)
iterable?(guard) ? PIterableType.new(self) : nil
end
# @api private
def runtime_type_name
@name_or_pattern.is_a?(String) ? @name_or_pattern : nil
end
# @api private
def class_or_module
raise "Only ruby classes or modules can be produced by this runtime, got '#{runtime}" unless runtime == :ruby
raise 'A pattern based Runtime type cannot produce a class or module' if @name_or_pattern.is_a?(Array)
com = ClassLoader.provide(self)
raise "The name #{@name_or_pattern} does not represent a ruby class or module" if com.nil?
com
end
# @api private
def from_puppet_name(puppet_name)
if @name_or_pattern.is_a?(Array)
substituted = puppet_name.sub(*@name_or_pattern)
substituted == puppet_name ? nil : PRuntimeType.new(@runtime, substituted)
else
nil
end
end
DEFAULT = PRuntimeType.new(nil, nil)
RUBY = PRuntimeType.new(:ruby, nil)
protected
# Assignable if o's has the same runtime and the runtime name resolves to
# a class that is the same or subclass of t1's resolved runtime type name
# @api private
def _assignable?(o, guard)
return false unless o.is_a?(PRuntimeType)
return false unless @runtime.nil? || @runtime == o.runtime
return true if @name_or_pattern.nil? # t1 is wider
onp = o.name_or_pattern
return true if @name_or_pattern == onp
return false unless @name_or_pattern.is_a?(String) && onp.is_a?(String)
# NOTE: This only supports Ruby, must change when/if the set of runtimes is expanded
begin
c1 = ClassLoader.provide(self)
c2 = ClassLoader.provide(o)
c1.is_a?(Module) && c2.is_a?(Module) && !!(c2 <= c1)
rescue ArgumentError
false
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/iterable.rb | lib/puppet/pops/types/iterable.rb | # frozen_string_literal: true
module Puppet::Pops::Types
# Implemented by classes that can produce an iterator to iterate over their contents
module IteratorProducer
def iterator
raise ArgumentError, 'iterator() is not implemented'
end
end
# The runtime Iterable type for an Iterable
module Iterable
# Produces an `Iterable` for one of the following types with the following characterstics:
#
# `String` - yields each character in the string
# `Array` - yields each element in the array
# `Hash` - yields each key/value pair as a two element array
# `Integer` - when positive, yields each value from zero to the given number
# `PIntegerType` - yields each element from min to max (inclusive) provided min < max and neither is unbounded.
# `PEnumtype` - yields each possible value of the enum.
# `Range` - yields an iterator for all elements in the range provided that the range start and end
# are both integers or both strings and start is less than end using natural ordering.
# `Dir` - yields each name in the directory
#
# An `ArgumentError` is raised for all other objects.
#
# @param my_caller [Object] The calling object to reference in errors
# @param obj [Object] The object to produce an `Iterable` for
# @param infer_elements [Boolean] Whether or not to recursively infer all elements of obj. Optional
#
# @return [Iterable,nil] The produced `Iterable`
# @raise [ArgumentError] In case an `Iterable` cannot be produced
# @api public
def self.asserted_iterable(my_caller, obj, infer_elements = false)
iter = on(obj, nil, infer_elements)
raise ArgumentError, "#{my_caller.class}(): wrong argument type (#{obj.class}; is not Iterable." if iter.nil?
iter
end
# Produces an `Iterable` for one of the following types with the following characteristics:
#
# `String` - yields each character in the string
# `Array` - yields each element in the array
# `Hash` - yields each key/value pair as a two element array
# `Integer` - when positive, yields each value from zero to the given number
# `PIntegerType` - yields each element from min to max (inclusive) provided min < max and neither is unbounded.
# `PEnumtype` - yields each possible value of the enum.
# `Range` - yields an iterator for all elements in the range provided that the range start and end
# are both integers or both strings and start is less than end using natural ordering.
# `Dir` - yields each name in the directory
#
# The value `nil` is returned for all other objects.
#
# @param o [Object] The object to produce an `Iterable` for
# @param element_type [PAnyType] the element type for the iterator. Optional
# @param infer_elements [Boolean] if element_type is nil, whether or not to recursively
# infer types for the entire collection. Optional
#
# @return [Iterable,nil] The produced `Iterable` or `nil` if it couldn't be produced
#
# @api public
def self.on(o, element_type = nil, infer_elements = true)
case o
when IteratorProducer
o.iterator
when Iterable
o
when String
Iterator.new(PStringType.new(PIntegerType.new(1, 1)), o.each_char)
when Array
if o.empty?
Iterator.new(PUnitType::DEFAULT, o.each)
else
if element_type.nil? && infer_elements
tc = TypeCalculator.singleton
element_type = PVariantType.maybe_create(o.map { |e| tc.infer_set(e) })
end
Iterator.new(element_type, o.each)
end
when Hash
# Each element is a two element [key, value] tuple.
if o.empty?
HashIterator.new(PHashType::DEFAULT_KEY_PAIR_TUPLE, o.each)
else
if element_type.nil? && infer_elements
tc = TypeCalculator.singleton
element_type =
PTupleType
.new([
PVariantType.maybe_create(o.keys.map { |e| tc.infer_set(e) }),
PVariantType.maybe_create(o.values.map { |e| tc.infer_set(e) })
],
PHashType::KEY_PAIR_TUPLE_SIZE)
end
HashIterator.new(element_type, o.each_pair)
end
when Integer
if o == 0
Iterator.new(PUnitType::DEFAULT, o.times)
elsif o > 0
IntegerRangeIterator.new(PIntegerType.new(0, o - 1))
else
nil
end
when PIntegerType
# a finite range will always produce at least one element since it's inclusive
o.finite_range? ? IntegerRangeIterator.new(o) : nil
when PEnumType
Iterator.new(o, o.values.each)
when PTypeAliasType
on(o.resolved_type)
when Range
min = o.min
max = o.max
if min.is_a?(Integer) && max.is_a?(Integer) && max >= min
IntegerRangeIterator.new(PIntegerType.new(min, max))
elsif min.is_a?(String) && max.is_a?(String) && max >= min
# A generalized element type where only the size is inferred is used here since inferring the full
# range might waste a lot of memory.
if min.length < max.length
shortest = min
longest = max
else
shortest = max
longest = min
end
Iterator.new(PStringType.new(PIntegerType.new(shortest.length, longest.length)), o.each)
else
# Unsupported range. It's either descending or nonsensical for other reasons (float, mixed types, etc.)
nil
end
else
# Not supported. We cannot determine the element type
nil
end
end
# Answers the question if there is an end to the iteration. Puppet does not currently provide any unbounded
# iterables.
#
# @return [Boolean] `true` if the iteration is unbounded
def self.unbounded?(object)
case object
when Iterable
object.unbounded?
when String, Integer, Array, Hash, Enumerator, PIntegerType, PEnumType, Dir
false
else
TypeAsserter.assert_instance_of('', PIterableType::DEFAULT, object, false)
!object.respond_to?(:size)
end
end
def each(&block)
step(1, &block)
end
def element_type
PAnyType::DEFAULT
end
def reverse_each(&block)
# Default implementation cannot propagate reverse_each to a new enumerator so chained
# calls must put reverse_each last.
raise ArgumentError, 'reverse_each() is not implemented'
end
def step(step, &block)
# Default implementation cannot propagate step to a new enumerator so chained
# calls must put stepping last.
raise ArgumentError, 'step() is not implemented'
end
def to_a
raise Puppet::Error, 'Attempt to create an Array from an unbounded Iterable' if unbounded?
super
end
def hash_style?
false
end
def unbounded?
true
end
end
# @api private
class Iterator
# Note! We do not include Enumerable module here since that would make this class respond
# in a bad way to all enumerable methods. We want to delegate all those calls directly to
# the contained @enumeration
include Iterable
def initialize(element_type, enumeration)
@element_type = element_type
@enumeration = enumeration
end
def element_type
@element_type
end
def size
@enumeration.size
end
def respond_to_missing?(name, include_private)
@enumeration.respond_to?(name, include_private)
end
def method_missing(name, *arguments, &block)
@enumeration.send(name, *arguments, &block)
end
def next
@enumeration.next
end
def map(*args, &block)
@enumeration.map(*args, &block)
end
def reduce(*args, &block)
@enumeration.reduce(*args, &block)
end
def all?(&block)
@enumeration.all?(&block)
end
def any?(&block)
@enumeration.any?(&block)
end
def step(step, &block)
raise ArgumentError if step <= 0
r = self
r = r.step_iterator(step) if step > 1
if block_given?
begin
if block.arity == 1
loop { yield(r.next) }
else
loop { yield(*r.next) }
end
rescue StopIteration
end
self
else
r
end
end
def reverse_each(&block)
r = Iterator.new(@element_type, @enumeration.reverse_each)
block_given? ? r.each(&block) : r
end
def step_iterator(step)
StepIterator.new(@element_type, self, step)
end
def to_s
et = element_type
et.nil? ? 'Iterator-Value' : "Iterator[#{et.generalize}]-Value"
end
def unbounded?
Iterable.unbounded?(@enumeration)
end
end
# Special iterator used when iterating over hashes. Returns `true` for `#hash_style?` so that
# it is possible to differentiate between two element arrays and key => value associations
class HashIterator < Iterator
def hash_style?
true
end
end
# @api private
class StepIterator < Iterator
include Enumerable
def initialize(element_type, enumeration, step_size)
super(element_type, enumeration)
raise ArgumentError if step_size <= 0
@step_size = step_size
end
def next
result = @enumeration.next
skip = @step_size - 1
if skip > 0
begin
skip.times { @enumeration.next }
rescue StopIteration
end
end
result
end
def reverse_each(&block)
r = Iterator.new(@element_type, to_a.reverse_each)
block_given? ? r.each(&block) : r
end
def size
super / @step_size
end
end
# @api private
class IntegerRangeIterator < Iterator
include Enumerable
def initialize(range, step = 1)
raise ArgumentError if step == 0
@range = range
@step_size = step
@current = (step < 0 ? range.to : range.from) - step
end
def element_type
@range
end
def next
value = @current + @step_size
if @step_size < 0
raise StopIteration if value < @range.from
elsif value > @range.to
raise StopIteration
end
@current = value
end
def reverse_each(&block)
r = IntegerRangeIterator.new(@range, -@step_size)
block_given? ? r.each(&block) : r
end
def size
(@range.to - @range.from) / @step_size.abs
end
def step_iterator(step)
# The step iterator must use a range that has its logical end truncated at an even step boundary. This will
# fulfil two objectives:
# 1. The element_type method should not report excessive integers as possible numbers
# 2. A reversed iterator must start at the correct number
#
range = @range
step = @step_size * step
mod = (range.to - range.from) % step
if mod < 0
range = PIntegerType.new(range.from - mod, range.to)
elsif mod > 0
range = PIntegerType.new(range.from, range.to - mod)
end
IntegerRangeIterator.new(range, step)
end
def unbounded?
false
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/type_parser.rb | lib/puppet/pops/types/type_parser.rb | # frozen_string_literal: true
require_relative '../../../puppet/concurrent/thread_local_singleton'
# This class provides parsing of Type Specification from a string into the Type
# Model that is produced by the TypeFactory.
#
# The Type Specifications that are parsed are the same as the stringified forms
# of types produced by the {TypeCalculator TypeCalculator}.
#
# @api public
module Puppet::Pops
module Types
class TypeParser
extend Puppet::Concurrent::ThreadLocalSingleton
# @api public
def initialize
@parser = Parser::Parser.new
@type_transformer = Visitor.new(nil, 'interpret', 1, 1)
end
# Produces a *puppet type* based on the given string.
#
# @example
# parser.parse('Integer')
# parser.parse('Array[String]')
# parser.parse('Hash[Integer, Array[String]]')
#
# @param string [String] a string with the type expressed in stringified form as produced by the
# types {"#to_s} method.
# @param context [Loader::Loader] optional loader used as no adapted loader is found
# @return [PAnyType] a specialization of the PAnyType representing the type.
#
# @api public
#
def parse(string, context = nil)
# quick "peephole" optimization of common data types
t = self.class.opt_type_map[string]
if t
return t
end
model = @parser.parse_string(string)
interpret(model.model.body, context)
end
# @api private
def parse_literal(string, context = nil)
factory = @parser.parse_string(string)
interpret_any(factory.model.body, context)
end
# @param ast [Puppet::Pops::Model::PopsObject] the ast to interpret
# @param context [Loader::Loader] optional loader used when no adapted loader is found
# @return [PAnyType] a specialization of the PAnyType representing the type.
#
# @api public
def interpret(ast, context = nil)
result = @type_transformer.visit_this_1(self, ast, context)
raise_invalid_type_specification_error(ast) unless result.is_a?(PAnyType)
result
end
# @api private
def interpret_any(ast, context)
@type_transformer.visit_this_1(self, ast, context)
end
# @api private
def interpret_Object(o, context)
raise_invalid_type_specification_error(o)
end
# @api private
def interpret_Program(o, context)
interpret_any(o.body, context)
end
# @api private
def interpret_TypeAlias(o, context)
Loader::TypeDefinitionInstantiator.create_type(o.name, o.type_expr, Pcore::RUNTIME_NAME_AUTHORITY).resolve(loader_from_context(o, context))
end
# @api private
def interpret_TypeDefinition(o, context)
Loader::TypeDefinitionInstantiator.create_runtime_type(o)
end
# @api private
def interpret_LambdaExpression(o, context)
o
end
# @api private
def interpret_HeredocExpression(o, context)
interpret_any(o.text_expr, context)
end
# @api private
def interpret_QualifiedName(o, context)
o.value
end
# @api private
def interpret_LiteralBoolean(o, context)
o.value
end
# @api private
def interpret_LiteralDefault(o, context)
:default
end
# @api private
def interpret_LiteralFloat(o, context)
o.value
end
# @api private
def interpret_LiteralHash(o, context)
result = {}
o.entries.each do |entry|
result[@type_transformer.visit_this_1(self, entry.key, context)] = @type_transformer.visit_this_1(self, entry.value, context)
end
result
end
# @api private
def interpret_LiteralInteger(o, context)
o.value
end
# @api private
def interpret_LiteralList(o, context)
o.values.map { |value| @type_transformer.visit_this_1(self, value, context) }
end
# @api private
def interpret_LiteralRegularExpression(o, context)
o.value
end
# @api private
def interpret_LiteralString(o, context)
o.value
end
# @api private
def interpret_LiteralUndef(o, context)
nil
end
# @api private
def interpret_String(o, context)
o
end
# @api private
def interpret_UnaryMinusExpression(o, context)
-@type_transformer.visit_this_1(self, o.expr, context)
end
# @api private
def self.type_map
@type_map ||= {
'integer' => TypeFactory.integer,
'float' => TypeFactory.float,
'numeric' => TypeFactory.numeric,
'init' => TypeFactory.init,
'iterable' => TypeFactory.iterable,
'iterator' => TypeFactory.iterator,
'string' => TypeFactory.string,
'binary' => TypeFactory.binary,
'sensitive' => TypeFactory.sensitive,
'enum' => TypeFactory.enum,
'boolean' => TypeFactory.boolean,
'pattern' => TypeFactory.pattern,
'regexp' => TypeFactory.regexp,
'array' => TypeFactory.array_of_any,
'hash' => TypeFactory.hash_of_any,
'class' => TypeFactory.host_class,
'resource' => TypeFactory.resource,
'collection' => TypeFactory.collection,
'scalar' => TypeFactory.scalar,
'scalardata' => TypeFactory.scalar_data,
'catalogentry' => TypeFactory.catalog_entry,
'undef' => TypeFactory.undef,
'notundef' => TypeFactory.not_undef,
'default' => TypeFactory.default,
'any' => TypeFactory.any,
'variant' => TypeFactory.variant,
'optional' => TypeFactory.optional,
'runtime' => TypeFactory.runtime,
'type' => TypeFactory.type_type,
'tuple' => TypeFactory.tuple,
'struct' => TypeFactory.struct,
'object' => TypeFactory.object,
'typealias' => TypeFactory.type_alias,
'typereference' => TypeFactory.type_reference,
'typeset' => TypeFactory.type_set,
# A generic callable as opposed to one that does not accept arguments
'callable' => TypeFactory.all_callables,
'semver' => TypeFactory.sem_ver,
'semverrange' => TypeFactory.sem_ver_range,
'timestamp' => TypeFactory.timestamp,
'timespan' => TypeFactory.timespan,
'uri' => TypeFactory.uri,
}.freeze
end
# @api private
def self.opt_type_map
# Map of common (and simple to optimize) data types in string form
# (Note that some types are the result of evaluation even if they appear to be simple
# - for example 'Data' and they cannot be optimized this way since the factory calls
# back to the parser for evaluation).
#
@opt_type_map ||= {
'Integer' => TypeFactory.integer,
'Float' => TypeFactory.float,
'Numeric' => TypeFactory.numeric,
'String' => TypeFactory.string,
'String[1]' => TypeFactory.string(TypeFactory.range(1, :default)),
'Binary' => TypeFactory.binary,
'Boolean' => TypeFactory.boolean,
'Boolean[true]' => TypeFactory.boolean(true),
'Boolean[false]' => TypeFactory.boolean(false),
'Array' => TypeFactory.array_of_any,
'Array[1]' => TypeFactory.array_of(TypeFactory.any, TypeFactory.range(1, :default)),
'Hash' => TypeFactory.hash_of_any,
'Collection' => TypeFactory.collection,
'Scalar' => TypeFactory.scalar,
'Scalardata' => TypeFactory.scalar_data,
'ScalarData' => TypeFactory.scalar_data,
'Catalogentry' => TypeFactory.catalog_entry,
'CatalogEntry' => TypeFactory.catalog_entry,
'Undef' => TypeFactory.undef,
'Default' => TypeFactory.default,
'Any' => TypeFactory.any,
'Type' => TypeFactory.type_type,
'Callable' => TypeFactory.all_callables,
'Semver' => TypeFactory.sem_ver,
'SemVer' => TypeFactory.sem_ver,
'Semverrange' => TypeFactory.sem_ver_range,
'SemVerRange' => TypeFactory.sem_ver_range,
'Timestamp' => TypeFactory.timestamp,
'TimeStamp' => TypeFactory.timestamp,
'Timespan' => TypeFactory.timespan,
'TimeSpan' => TypeFactory.timespan,
'Uri' => TypeFactory.uri,
'URI' => TypeFactory.uri,
'Optional[Integer]' => TypeFactory.optional(TypeFactory.integer),
'Optional[String]' => TypeFactory.optional(TypeFactory.string),
'Optional[String[1]]' => TypeFactory.optional(TypeFactory.string(TypeFactory.range(1, :default))),
'Optional[Array]' => TypeFactory.optional(TypeFactory.array_of_any),
'Optional[Hash]' => TypeFactory.optional(TypeFactory.hash_of_any),
}.freeze
end
# @api private
def interpret_QualifiedReference(name_ast, context)
name = name_ast.value
found = self.class.type_map[name]
if found
found
else
loader = loader_from_context(name_ast, context)
unless loader.nil?
type = loader.load(:type, name)
type = type.resolve(loader) unless type.nil?
end
type || TypeFactory.type_reference(name_ast.cased_value)
end
end
# @api private
def loader_from_context(ast, context)
model_loader = Adapters::LoaderAdapter.loader_for_model_object(ast, nil, context)
if context.is_a?(PTypeSetType::TypeSetLoader)
# Only swap a given TypeSetLoader for another loader when the other loader is different
# from the one associated with the TypeSet expression
context.model_loader.equal?(model_loader.parent) ? context : model_loader
else
model_loader
end
end
# @api private
def interpret_AccessExpression(ast, context)
parameters = ast.keys.collect { |param| interpret_any(param, context) }
qref = ast.left_expr
raise_invalid_type_specification_error(ast) unless qref.is_a?(Model::QualifiedReference)
type_name = qref.value
case type_name
when 'array'
case parameters.size
when 1
type = assert_type(ast, parameters[0])
when 2
if parameters[0].is_a?(PAnyType)
type = parameters[0]
size_type =
if parameters[1].is_a?(PIntegerType)
size_type = parameters[1]
else
assert_range_parameter(ast, parameters[1])
TypeFactory.range(parameters[1], :default)
end
else
type = :default
assert_range_parameter(ast, parameters[0])
assert_range_parameter(ast, parameters[1])
size_type = TypeFactory.range(parameters[0], parameters[1])
end
when 3
type = assert_type(ast, parameters[0])
assert_range_parameter(ast, parameters[1])
assert_range_parameter(ast, parameters[2])
size_type = TypeFactory.range(parameters[1], parameters[2])
else
raise_invalid_parameters_error('Array', '1 to 3', parameters.size)
end
TypeFactory.array_of(type, size_type)
when 'hash'
case parameters.size
when 2
if parameters[0].is_a?(PAnyType) && parameters[1].is_a?(PAnyType)
TypeFactory.hash_of(parameters[1], parameters[0])
else
assert_range_parameter(ast, parameters[0])
assert_range_parameter(ast, parameters[1])
TypeFactory.hash_of(:default, :default, TypeFactory.range(parameters[0], parameters[1]))
end
when 3
size_type =
if parameters[2].is_a?(PIntegerType)
parameters[2]
else
assert_range_parameter(ast, parameters[2])
TypeFactory.range(parameters[2], :default)
end
assert_type(ast, parameters[0])
assert_type(ast, parameters[1])
TypeFactory.hash_of(parameters[1], parameters[0], size_type)
when 4
assert_range_parameter(ast, parameters[2])
assert_range_parameter(ast, parameters[3])
assert_type(ast, parameters[0])
assert_type(ast, parameters[1])
TypeFactory.hash_of(parameters[1], parameters[0], TypeFactory.range(parameters[2], parameters[3]))
else
raise_invalid_parameters_error('Hash', '2 to 4', parameters.size)
end
when 'collection'
size_type = case parameters.size
when 1
if parameters[0].is_a?(PIntegerType)
parameters[0]
else
assert_range_parameter(ast, parameters[0])
TypeFactory.range(parameters[0], :default)
end
when 2
assert_range_parameter(ast, parameters[0])
assert_range_parameter(ast, parameters[1])
TypeFactory.range(parameters[0], parameters[1])
else
raise_invalid_parameters_error('Collection', '1 to 2',
parameters.size)
end
TypeFactory.collection(size_type)
when 'class'
if parameters.size != 1
raise_invalid_parameters_error('Class', 1, parameters.size)
end
TypeFactory.host_class(parameters[0])
when 'resource'
type = parameters[0]
if type.is_a?(PTypeReferenceType)
type_str = type.type_string
param_start = type_str.index('[')
if param_start.nil?
type = type_str
else
tps = interpret_any(@parser.parse_string(type_str[param_start..]).model, context)
raise_invalid_parameters_error(type.to_s, '1', tps.size) unless tps.size == 1
type = type_str[0..param_start - 1]
parameters = [type] + tps
end
end
create_resource(type, parameters)
when 'regexp'
# 1 parameter being a string, or regular expression
raise_invalid_parameters_error('Regexp', '1', parameters.size) unless parameters.size == 1
TypeFactory.regexp(parameters[0])
when 'enum'
# 1..m parameters being string
last = parameters.last
case_insensitive = false
if last == true || last == false
parameters = parameters[0...-1]
case_insensitive = last
end
raise_invalid_parameters_error('Enum', '1 or more', parameters.size) unless parameters.size >= 1
parameters.each { |p| raise Puppet::ParseError, _('Enum parameters must be identifiers or strings') unless p.is_a?(String) }
PEnumType.new(parameters, case_insensitive)
when 'pattern'
# 1..m parameters being strings or regular expressions
raise_invalid_parameters_error('Pattern', '1 or more', parameters.size) unless parameters.size >= 1
TypeFactory.pattern(*parameters)
when 'uri'
# 1 parameter which is a string or a URI
raise_invalid_parameters_error('URI', '1', parameters.size) unless parameters.size == 1
TypeFactory.uri(parameters[0])
when 'variant'
# 1..m parameters being strings or regular expressions
raise_invalid_parameters_error('Variant', '1 or more', parameters.size) unless parameters.size >= 1
parameters.each { |p| assert_type(ast, p) }
TypeFactory.variant(*parameters)
when 'tuple'
# 1..m parameters being types (last two optionally integer or literal default
raise_invalid_parameters_error('Tuple', '1 or more', parameters.size) unless parameters.size >= 1
length = parameters.size
size_type = nil
if TypeFactory.is_range_parameter?(parameters[-2])
# min, max specification
min = parameters[-2]
min = (min == :default || min == 'default') ? 0 : min
assert_range_parameter(ast, parameters[-1])
max = parameters[-1]
max = max == :default ? nil : max
parameters = parameters[0, length - 2]
size_type = TypeFactory.range(min, max)
elsif TypeFactory.is_range_parameter?(parameters[-1])
min = parameters[-1]
min = (min == :default || min == 'default') ? 0 : min
max = nil
parameters = parameters[0, length - 1]
size_type = TypeFactory.range(min, max)
end
TypeFactory.tuple(parameters, size_type)
when 'callable'
# 1..m parameters being types (last three optionally integer or literal default, and a callable)
if parameters.size > 1 && parameters[0].is_a?(Array)
raise_invalid_parameters_error('callable', '2 when first parameter is an array', parameters.size) unless parameters.size == 2
end
TypeFactory.callable(*parameters)
when 'struct'
# 1..m parameters being types (last two optionally integer or literal default
raise_invalid_parameters_error('Struct', '1', parameters.size) unless parameters.size == 1
h = parameters[0]
raise_invalid_type_specification_error(ast) unless h.is_a?(Hash)
TypeFactory.struct(h)
when 'boolean'
raise_invalid_parameters_error('Boolean', '1', parameters.size) unless parameters.size == 1
p = parameters[0]
raise Puppet::ParseError, 'Boolean parameter must be true or false' unless p == true || p == false
TypeFactory.boolean(p)
when 'integer'
if parameters.size == 1
case parameters[0]
when Integer
TypeFactory.range(parameters[0], :default)
when :default
TypeFactory.integer # unbound
end
elsif parameters.size != 2
raise_invalid_parameters_error('Integer', '1 or 2', parameters.size)
else
TypeFactory.range(parameters[0] == :default ? nil : parameters[0], parameters[1] == :default ? nil : parameters[1])
end
when 'object'
raise_invalid_parameters_error('Object', 1, parameters.size) unless parameters.size == 1
TypeFactory.object(parameters[0])
when 'typeset'
raise_invalid_parameters_error('Object', 1, parameters.size) unless parameters.size == 1
TypeFactory.type_set(parameters[0])
when 'init'
assert_type(ast, parameters[0])
TypeFactory.init(*parameters)
when 'iterable'
if parameters.size != 1
raise_invalid_parameters_error('Iterable', 1, parameters.size)
end
assert_type(ast, parameters[0])
TypeFactory.iterable(parameters[0])
when 'iterator'
if parameters.size != 1
raise_invalid_parameters_error('Iterator', 1, parameters.size)
end
assert_type(ast, parameters[0])
TypeFactory.iterator(parameters[0])
when 'float'
if parameters.size == 1
case parameters[0]
when Integer, Float
TypeFactory.float_range(parameters[0], :default)
when :default
TypeFactory.float # unbound
end
elsif parameters.size != 2
raise_invalid_parameters_error('Float', '1 or 2', parameters.size)
else
TypeFactory.float_range(parameters[0] == :default ? nil : parameters[0], parameters[1] == :default ? nil : parameters[1])
end
when 'string'
size_type =
case parameters.size
when 1
if parameters[0].is_a?(PIntegerType)
parameters[0]
else
assert_range_parameter(ast, parameters[0])
TypeFactory.range(parameters[0], :default)
end
when 2
assert_range_parameter(ast, parameters[0])
assert_range_parameter(ast, parameters[1])
TypeFactory.range(parameters[0], parameters[1])
else
raise_invalid_parameters_error('String', '1 to 2', parameters.size)
end
TypeFactory.string(size_type)
when 'sensitive'
case parameters.size
when 0
TypeFactory.sensitive
when 1
param = parameters[0]
assert_type(ast, param)
TypeFactory.sensitive(param)
else
raise_invalid_parameters_error('Sensitive', '0 to 1', parameters.size)
end
when 'optional'
if parameters.size != 1
raise_invalid_parameters_error('Optional', 1, parameters.size)
end
param = parameters[0]
assert_type(ast, param) unless param.is_a?(String)
TypeFactory.optional(param)
when 'any', 'data', 'catalogentry', 'scalar', 'undef', 'numeric', 'default', 'semverrange'
raise_unparameterized_type_error(qref)
when 'notundef'
case parameters.size
when 0
TypeFactory.not_undef
when 1
param = parameters[0]
assert_type(ast, param) unless param.is_a?(String)
TypeFactory.not_undef(param)
else
raise_invalid_parameters_error("NotUndef", "0 to 1", parameters.size)
end
when 'type'
if parameters.size != 1
raise_invalid_parameters_error('Type', 1, parameters.size)
end
assert_type(ast, parameters[0])
TypeFactory.type_type(parameters[0])
when 'runtime'
raise_invalid_parameters_error('Runtime', '2', parameters.size) unless parameters.size == 2
TypeFactory.runtime(*parameters)
when 'timespan'
raise_invalid_parameters_error('Timespan', '0 to 2', parameters.size) unless parameters.size <= 2
TypeFactory.timespan(*parameters)
when 'timestamp'
raise_invalid_parameters_error('Timestamp', '0 to 2', parameters.size) unless parameters.size <= 2
TypeFactory.timestamp(*parameters)
when 'semver'
raise_invalid_parameters_error('SemVer', '1 or more', parameters.size) unless parameters.size >= 1
TypeFactory.sem_ver(*parameters)
else
loader = loader_from_context(qref, context)
type = nil
unless loader.nil?
type = loader.load(:type, type_name)
type = type.resolve(loader) unless type.nil?
end
if type.nil?
TypeFactory.type_reference(original_text_of(ast))
elsif type.is_a?(PResourceType)
raise_invalid_parameters_error(qref.cased_value, 1, parameters.size) unless parameters.size == 1
TypeFactory.resource(type.type_name, parameters[0])
elsif type.is_a?(PObjectType)
PObjectTypeExtension.create(type, parameters)
else
# Must be a type alias. They can't use parameters (yet)
raise_unparameterized_type_error(qref)
end
end
end
private
def create_resource(name, parameters)
case parameters.size
when 1
TypeFactory.resource(name)
when 2
TypeFactory.resource(name, parameters[1])
else
raise_invalid_parameters_error('Resource', '1 or 2', parameters.size)
end
end
def assert_type(ast, t)
raise_invalid_type_specification_error(ast) unless t.is_a?(PAnyType)
t
end
def assert_range_parameter(ast, t)
raise_invalid_type_specification_error(ast) unless TypeFactory.is_range_parameter?(t)
end
def raise_invalid_type_specification_error(ast)
raise Puppet::ParseError, _("The expression <%{expression}> is not a valid type specification.") %
{ expression: original_text_of(ast) }
end
def raise_invalid_parameters_error(type, required, given)
raise Puppet::ParseError, _("Invalid number of type parameters specified: %{type} requires %{required}, %{given} provided") %
{ type: type, required: required, given: given }
end
def raise_unparameterized_type_error(ast)
raise Puppet::ParseError, _("Not a parameterized type <%{type}>") % { type: original_text_of(ast) }
end
def raise_unknown_type_error(ast)
raise Puppet::ParseError, _("Unknown type <%{type}>") % { type: original_text_of(ast) }
end
def original_text_of(ast)
ast.locator.extract_tree_text(ast)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/p_sensitive_type.rb | lib/puppet/pops/types/p_sensitive_type.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
# A Puppet Language type that wraps sensitive information. The sensitive type is parameterized by
# the wrapped value type.
#
#
# @api public
class PSensitiveType < PTypeWithContainedType
class Sensitive
def initialize(value)
@value = value
end
def unwrap
@value
end
def to_s
"Sensitive [value redacted]"
end
def inspect
"#<#{self}>"
end
def hash
@value.hash
end
def ==(other)
other.is_a?(Sensitive) &&
other.hash == hash
end
alias eql? ==
end
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'AnyType')
end
def initialize(type = nil)
@type = type.nil? ? PAnyType.new : type.generalize
end
def instance?(o, guard = nil)
o.is_a?(Sensitive) && @type.instance?(o.unwrap, guard)
end
def self.new_function(type)
@new_function ||= Puppet::Functions.create_loaded_function(:new_Sensitive, type.loader) do
dispatch :from_sensitive do
param 'Sensitive', :value
end
dispatch :from_any do
param 'Any', :value
end
def from_any(value)
Sensitive.new(value)
end
# Since the Sensitive value is immutable we can reuse the existing instance instead of making a copy.
def from_sensitive(value)
value
end
end
end
private
def _assignable?(o, guard)
instance_of?(o.class) && @type.assignable?(o.type, guard)
end
DEFAULT = PSensitiveType.new
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/p_object_type_extension.rb | lib/puppet/pops/types/p_object_type_extension.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
# Base class for Parameterized Object implementations. The wrapper impersonates the base
# object and extends it with methods to filter assignable types and instances based on parameter
# values.
#
# @api public
class PObjectTypeExtension < PAnyType
include TypeWithMembers
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'AnyType',
'base_type' => {
KEY_TYPE => PTypeType::DEFAULT
},
'init_parameters' => {
KEY_TYPE => PArrayType::DEFAULT
})
end
attr_reader :base_type, :parameters
# @api private
def self.create(base_type, init_parameters)
impl_class = Loaders.implementation_registry.module_for_type("#{base_type.name}TypeExtension") || self
impl_class.new(base_type, init_parameters)
end
# Creates an array of type parameters from the attributes of the given instance that matches the
# type parameters by name. Type parameters for which there is no matching attribute
# will have `nil` in their corresponding position on the array. The array is then passed
# as the `init_parameters` argument in a call to `create`
#
# @return [PObjectTypeExtension] the created extension
# @api private
def self.create_from_instance(base_type, instance)
type_parameters = base_type.type_parameters(true)
attrs = base_type.attributes(true)
params = type_parameters.keys.map do |pn|
attr = attrs[pn]
attr.nil? ? nil : instance.send(pn)
end
create(base_type, params)
end
def [](name)
@base_type[name]
end
# @api private
def initialize(base_type, init_parameters)
pts = base_type.type_parameters(true)
raise Puppet::ParseError, _('The %{label}-Type cannot be parameterized using []') % { label: base_type.label } if pts.empty?
@base_type = base_type
named_args = init_parameters.size == 1 && init_parameters[0].is_a?(Hash)
if named_args
# Catch case when first parameter is an assignable Hash
named_args = pts.size >= 1 && !pts.values[0].type.instance?(init_parameters[0])
end
by_name = {}
if named_args
hash = init_parameters[0]
hash.each_pair do |pn, pv|
tp = pts[pn]
if tp.nil?
raise Puppet::ParseError, _("'%{pn}' is not a known type parameter for %{label}-Type") % { pn: pn, label: base_type.label }
end
by_name[pn] = check_param(tp, pv) unless pv == :default
end
else
pts.values.each_with_index do |tp, idx|
if idx < init_parameters.size
pv = init_parameters[idx]
by_name[tp.name] = check_param(tp, pv) unless pv == :default
end
end
end
if by_name.empty?
raise Puppet::ParseError, _('The %{label}-Type cannot be parameterized using an empty parameter list') % { label: base_type.label }
end
@parameters = by_name
end
def check_param(type_param, v)
TypeAsserter.assert_instance_of(nil, type_param.type, v) { type_param.label }
end
# Return the parameter values as positional arguments with unset values as :default. The
# array is stripped from trailing :default values
# @return [Array] the parameter values
# @api private
def init_parameters
pts = @base_type.type_parameters(true)
if pts.size > 2
@parameters
else
result = pts.values.map do |tp|
pn = tp.name
@parameters.include?(pn) ? @parameters[pn] : :default
end
# Remove trailing defaults
result.pop while result.last == :default
result
end
end
# @api private
def eql?(o)
super(o) && @base_type.eql?(o.base_type) && @parameters.eql?(o.parameters)
end
# @api private
def generalize
@base_type
end
# @api private
def hash
@base_type.hash ^ @parameters.hash
end
# @api private
def loader
@base_type.loader
end
# @api private
def check_self_recursion(originator)
@base_type.check_self_recursion(originator)
end
# @api private
def create(*args)
@base_type.create(*args)
end
# @api private
def instance?(o, guard = nil)
@base_type.instance?(o, guard) && test_instance?(o, guard)
end
# @api private
def new_function
@base_type.new_function
end
# @api private
def simple_name
@base_type.simple_name
end
# @api private
def implementation_class(create = true)
@base_type.implementation_class(create)
end
# @api private
def parameter_info(impl_class)
@base_type.parameter_info(impl_class)
end
protected
# Checks that the given `param_values` hash contains all keys present in the `parameters` of
# this instance and that each keyed value is a match for the given parameter. The match is done
# using case expression semantics.
#
# This method is only called when a given type is found to be assignable to the base type of
# this extension.
#
# @param param_values[Hash] the parameter values of the assignable type
# @param guard[RecursionGuard] guard against endless recursion
# @return [Boolean] true or false to indicate assignability
# @api public
def test_assignable?(param_values, guard)
# Default implementation performs case expression style matching of all parameter values
# provided that the value exist (this should always be the case, since all defaults have
# been assigned at this point)
eval = Parser::EvaluatingParser.singleton.evaluator
@parameters.keys.all? do |pn|
if param_values.include?(pn)
a = param_values[pn]
b = @parameters[pn]
eval.match?(a, b) || a.is_a?(PAnyType) && b.is_a?(PAnyType) && b.assignable?(a)
else
false
end
end
end
# Checks that the given instance `o` has one attribute for each key present in the `parameters` of
# this instance and that each attribute value is a match for the given parameter. The match is done
# using case expression semantics.
#
# This method is only called when the given value is found to be an instance of the base type of
# this extension.
#
# @param o [Object] the instance to test
# @param guard[RecursionGuard] guard against endless recursion
# @return [Boolean] true or false to indicate if the value is an instance or not
# @api public
def test_instance?(o, guard)
eval = Parser::EvaluatingParser.singleton.evaluator
@parameters.keys.all? do |pn|
m = o.public_method(pn)
m.arity == 0 ? eval.match?(m.call, @parameters[pn]) : false
rescue NameError
false
end
end
# @api private
def _assignable?(o, guard = nil)
if o.is_a?(PObjectTypeExtension)
@base_type.assignable?(o.base_type, guard) && test_assignable?(o.parameters, guard)
else
@base_type.assignable?(o, guard) && test_assignable?(EMPTY_HASH, guard)
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/string_converter.rb | lib/puppet/pops/types/string_converter.rb | # frozen_string_literal: true
require_relative '../../../puppet/concurrent/thread_local_singleton'
module Puppet::Pops
module Types
# Converts Puppet runtime objects to String under the control of a Format.
# Use from Puppet Language is via the function `new`.
#
# @api private
#
class StringConverter
# @api private
class FormatError < ArgumentError
def initialize(type_string, actual, expected)
super "Illegal format '#{actual}' specified for value of #{type_string} type - expected one of the characters '#{expected}'"
end
end
class Indentation
attr_reader :level
attr_reader :first
attr_reader :is_indenting
alias :first? :first
alias :is_indenting? :is_indenting
def initialize(level, first, is_indenting)
@level = level
@first = first
@is_indenting = is_indenting
end
def subsequent
first? ? self.class.new(level, false, @is_indenting) : self
end
def indenting(indenting_flag)
self.class.new(level, first?, indenting_flag)
end
def increase(indenting_flag = false)
self.class.new(level + 1, true, indenting_flag)
end
def breaks?
is_indenting? && level > 0 && !first?
end
def padding
' ' * 2 * level
end
end
# Format represents one format specification that is textually represented by %<flags><width>.<precision><format>
# Format parses and makes the individual parts available when an instance is created.
#
# @api private
#
class Format
# Boolean, alternate form (varies in meaning)
attr_reader :alt
alias :alt? :alt
# Nil or Integer with width of field > 0
attr_reader :width
# Nil or Integer precisions
attr_reader :prec
# One char symbol denoting the format
attr_reader :format
# Symbol, :space, :plus, :ignore
attr_reader :plus
# Boolean, left adjust in given width or not
attr_reader :left
# Boolean left_pad with zero instead of space
attr_reader :zero_pad
# Delimiters for containers, a "left" char representing the pair <[{(
attr_reader :delimiters
# Map of type to format for elements contained in an object this format applies to
attr_accessor :container_string_formats
# Separator string inserted between elements in a container
attr_accessor :separator
# Separator string inserted between sub elements in a container
attr_accessor :separator2
attr_reader :orig_fmt
FMT_PATTERN_STR = '^%([\s\[+#0{<(|-]*)([1-9][0-9]*)?(?:\.([0-9]+))?([a-zA-Z])$'
FMT_PATTERN = Regexp.compile(FMT_PATTERN_STR)
DELIMITERS = ['[', '{', '(', '<', '|']
DELIMITER_MAP = {
'[' => ['[', ']'],
'{' => ['{', '}'],
'(' => ['(', ')'],
'<' => ['<', '>'],
'|' => ['|', '|'],
:space => ['', '']
}.freeze
def initialize(fmt)
@orig_fmt = fmt
match = FMT_PATTERN.match(fmt)
unless match
raise ArgumentError, "The format '#{fmt}' is not a valid format on the form '%<flags><width>.<prec><format>'"
end
@format = match[4]
unless @format.is_a?(String) && @format.length == 1
raise ArgumentError, "The format must be a one letter format specifier, got '#{@format}'"
end
@format = @format.to_sym
flags = match[1].split('') || []
unless flags.uniq.size == flags.size
raise ArgumentError, "The same flag can only be used once, got '#{fmt}'"
end
@left = flags.include?('-')
@alt = flags.include?('#')
@plus = if flags.include?(' ')
:space
else
flags.include?('+') ? :plus : :ignore
end
@zero_pad = flags.include?('0')
@delimiters = nil
DELIMITERS.each do |d|
next unless flags.include?(d)
unless @delimiters.nil?
raise ArgumentError, "Only one of the delimiters [ { ( < | can be given in the format flags, got '#{fmt}'"
end
@delimiters = d
end
@width = match[2] ? match[2].to_i : nil
@prec = match[3] ? match[3].to_i : nil
end
# Merges one format into this and returns a new `Format`. The `other` format overrides this.
# @param [Format] other
# @returns [Format] a merged format
#
def merge(other)
result = Format.new(other.orig_fmt)
result.separator = other.separator || separator
result.separator2 = other.separator2 || separator2
result.container_string_formats = Format.merge_string_formats(container_string_formats, other.container_string_formats)
result
end
# Merges two formats where the `higher` format overrides the `lower`. Produces a new `Format`
# @param [Format] lower
# @param [Format] higher
# @returns [Format] the merged result
#
def self.merge(lower, higher)
unless lower && higher
return lower || higher
end
lower.merge(higher)
end
# Merges a type => format association and returns a new merged and sorted association.
# @param [Format] lower
# @param [Format] higher
# @returns [Hash] the merged type => format result
#
def self.merge_string_formats(lower, higher)
unless lower && higher
return lower || higher
end
# drop all formats in lower than is more generic in higher. Lower must never
# override higher
lower = lower.reject { |lk, _| higher.keys.any? { |hk| hk != lk && hk.assignable?(lk) } }
merged = (lower.keys + higher.keys).uniq.map do |k|
[k, merge(lower[k], higher[k])]
end
sort_formats(merged)
end
# Sorts format based on generality of types - most specific types before general
#
def self.sort_formats(format_map)
format_map = format_map.sort do |(a, _), (b, _)|
ab = b.assignable?(a)
ba = a.assignable?(b)
if a == b
0
elsif ab && !ba
-1
elsif !ab && ba
1
else
# arbitrary order if disjunct (based on name of type)
rank_a = type_rank(a)
rank_b = type_rank(b)
if rank_a == 0 || rank_b == 0
a.to_s <=> b.to_s
else
rank_a <=> rank_b
end
end
end
format_map.to_h
end
# Ranks type on specificity where it matters
# lower number means more specific
def self.type_rank(t)
case t
when PStructType
1
when PHashType
2
when PTupleType
3
when PArrayType
4
when PPatternType
10
when PEnumType
11
when PStringType
12
else
0
end
end
# Returns an array with a delimiter pair derived from the format.
# If format does not contain a delimiter specification the given default is returned
#
# @param [Array<String>] the default delimiters
# @returns [Array<String>] a tuple with left, right delimiters
#
def delimiter_pair(default = StringConverter::DEFAULT_ARRAY_DELIMITERS)
DELIMITER_MAP[@delimiters || @plus] || default
end
def to_s
"%#{@flags}#{@width}.#{@prec}#{@format}"
end
end
extend Puppet::Concurrent::ThreadLocalSingleton
# @api public
def self.convert(value, string_formats = :default)
singleton.convert(value, string_formats)
end
# @api private
#
def initialize
@string_visitor = Visitor.new(self, "string", 3, 3)
end
DEFAULT_INDENTATION = Indentation.new(0, true, false).freeze
# format used by default for values in a container
# (basically strings are quoted since they may contain a ','))
#
DEFAULT_CONTAINER_FORMATS = {
PAnyType::DEFAULT => Format.new('%p').freeze, # quoted string (Ruby inspect)
}.freeze
DEFAULT_ARRAY_FORMAT = Format.new('%a')
DEFAULT_ARRAY_FORMAT.separator = ', '
DEFAULT_ARRAY_FORMAT.separator2 = ', '
DEFAULT_ARRAY_FORMAT.container_string_formats = DEFAULT_CONTAINER_FORMATS
DEFAULT_ARRAY_FORMAT.freeze
DEFAULT_HASH_FORMAT = Format.new('%h')
DEFAULT_HASH_FORMAT.separator = ', '
DEFAULT_HASH_FORMAT.separator2 = ' => '
DEFAULT_HASH_FORMAT.container_string_formats = DEFAULT_CONTAINER_FORMATS
DEFAULT_HASH_FORMAT.freeze
DEFAULT_HASH_DELIMITERS = ['{', '}'].freeze
DEFAULT_ARRAY_DELIMITERS = ['[', ']'].freeze
DEFAULT_STRING_FORMATS = {
PObjectType::DEFAULT => Format.new('%p').freeze, # call with initialization hash
PFloatType::DEFAULT => Format.new('%f').freeze, # float
PNumericType::DEFAULT => Format.new('%d').freeze, # decimal number
PArrayType::DEFAULT => DEFAULT_ARRAY_FORMAT.freeze,
PHashType::DEFAULT => DEFAULT_HASH_FORMAT.freeze,
PBinaryType::DEFAULT => Format.new('%B').freeze, # strict base64 string unquoted
PAnyType::DEFAULT => Format.new('%s').freeze, # unquoted string
}.freeze
DEFAULT_PARAMETER_FORMAT = {
PCollectionType::DEFAULT => '%#p',
PObjectType::DEFAULT => '%#p',
PBinaryType::DEFAULT => '%p',
PStringType::DEFAULT => '%p',
PRuntimeType::DEFAULT => '%p'
}.freeze
# Converts the given value to a String, under the direction of formatting rules per type.
#
# When converting to string it is possible to use a set of built in conversion rules.
#
# A format is specified on the form:
#
# ´´´
# %[Flags][Width][.Precision]Format
# ´´´
#
# `Width` is the number of characters into which the value should be fitted. This allocated space is
# padded if value is shorter. By default it is space padded, and the flag 0 will cause padding with 0
# for numerical formats.
#
# `Precision` is the number of fractional digits to show for floating point, and the maximum characters
# included in a string format.
#
# Note that all data type supports the formats `s` and `p` with the meaning "default to-string" and
# "default-programmatic to-string".
#
# ### Integer
#
# | Format | Integer Formats
# | ------ | ---------------
# | d | Decimal, negative values produces leading '-'
# | x X | Hexadecimal in lower or upper case. Uses ..f/..F for negative values unless # is also used
# | o | Octal. Uses ..0 for negative values unless # is also used
# | b B | Binary with prefix 'b' or 'B'. Uses ..1/..1 for negative values unless # is also used
# | c | numeric value representing a Unicode value, result is a one unicode character string, quoted if alternative flag # is used
# | s | same as d, or d in quotes if alternative flag # is used
# | p | same as d
# | eEfgGaA | converts integer to float and formats using the floating point rules
#
# Defaults to `d`
#
# ### Float
#
# | Format | Float formats
# | ------ | -------------
# | f | floating point in non exponential notation
# | e E | exponential notation with 'e' or 'E'
# | g G | conditional exponential with 'e' or 'E' if exponent < -4 or >= the precision
# | a A | hexadecimal exponential form, using 'x'/'X' as prefix and 'p'/'P' before exponent
# | s | converted to string using format p, then applying string formatting rule, alternate form # quotes result
# | p | f format with minimum significant number of fractional digits, prec has no effect
# | dxXobBc | converts float to integer and formats using the integer rules
#
# Defaults to `p`
#
# ### String
#
# | Format | String
# | ------ | ------
# | s | unquoted string, verbatim output of control chars
# | p | programmatic representation - strings are quoted, interior quotes and control chars are escaped
# | C | each :: name segment capitalized, quoted if alternative flag # is used
# | c | capitalized string, quoted if alternative flag # is used
# | d | downcased string, quoted if alternative flag # is used
# | u | upcased string, quoted if alternative flag # is used
# | t | trims leading and trailing whitespace from the string, quoted if alternative flag # is used
#
# Defaults to `s` at top level and `p` inside array or hash.
#
# ### Boolean
#
# | Format | Boolean Formats
# | ---- | -------------------
# | t T | 'true'/'false' or 'True'/'False' , first char if alternate form is used (i.e. 't'/'f' or 'T'/'F').
# | y Y | 'yes'/'no', 'Yes'/'No', 'y'/'n' or 'Y'/'N' if alternative flag # is used
# | dxXobB | numeric value 0/1 in accordance with the given format which must be valid integer format
# | eEfgGaA | numeric value 0.0/1.0 in accordance with the given float format and flags
# | s | 'true' / 'false'
# | p | 'true' / 'false'
#
# ### Regexp
#
# | Format | Regexp Formats (%/)
# | ---- | ------------------
# | s | / / delimiters, alternate flag replaces / delimiters with quotes
# | p | / / delimiters
#
# ### Undef
#
# | Format | Undef formats
# | ------ | -------------
# | s | empty string, or quoted empty string if alternative flag # is used
# | p | 'undef', or quoted '"undef"' if alternative flag # is used
# | n | 'nil', or 'null' if alternative flag # is used
# | dxXobB | 'NaN'
# | eEfgGaA | 'NaN'
# | v | 'n/a'
# | V | 'N/A'
# | u | 'undef', or 'undefined' if alternative # flag is used
#
# ### Default (value)
#
# | Format | Default formats
# | ------ | ---------------
# | d D | 'default' or 'Default', alternative form # causes value to be quoted
# | s | same as d
# | p | same as d
#
# ### Binary (value)
#
# | Format | Default formats
# | ------ | ---------------
# | s | binary as unquoted characters
# | p | 'Binary("<base64strict>")'
# | b | '<base64>' - base64 string with newlines inserted
# | B | '<base64strict>' - base64 strict string (without newlines inserted)
# | u | '<base64urlsafe>' - base64 urlsafe string
# | t | 'Binary' - outputs the name of the type only
# | T | 'BINARY' - output the name of the type in all caps only
#
# The alternate form flag `#` will quote the binary or base64 text output
# The width and precision values are applied to the text part only in `%p` format.
#
# ### Array & Tuple
#
# | Format | Array/Tuple Formats
# | ------ | -------------
# | a | formats with `[ ]` delimiters and `,`, alternate form `#` indents nested arrays/hashes
# | s | same as a
# | p | same as a
#
# See "Flags" `<[({\|` for formatting of delimiters, and "Additional parameters for containers; Array and Hash" for
# more information about options.
#
# The alternate form flag `#` will cause indentation of nested array or hash containers. If width is also set
# it is taken as the maximum allowed length of a sequence of elements (not including delimiters). If this max length
# is exceeded, each element will be indented.
#
# ### Hash & Struct
#
# | Format | Hash/Struct Formats
# | ------ | -------------
# | h | formats with `{ }` delimiters, `,` element separator and ` => ` inner element separator unless overridden by flags
# | s | same as h
# | p | same as h
# | a | converts the hash to an array of [k,v] tuples and formats it using array rule(s)
#
# See "Flags" `<[({\|` for formatting of delimiters, and "Additional parameters for containers; Array and Hash" for
# more information about options.
#
# The alternate form flag `#` will format each hash key/value entry indented on a separate line.
#
# ### Type
#
# | Format | Array/Tuple Formats
# | ------ | -------------
# | s | The same as p, quoted if alternative flag # is used
# | p | Outputs the type in string form as specified by the Puppet Language
#
# ### Flags
#
# | Flag | Effect
# | ------ | ------
# | (space) | space instead of + for numeric output (- is shown), for containers skips delimiters
# | # | alternate format; prefix 0x/0x, 0 (octal) and 0b/0B for binary, Floats force decimal '.'. For g/G keep trailing 0.
# | + | show sign +/- depending on value's sign, changes x,X, o,b, B format to not use 2's complement form
# | - | left justify the value in the given width
# | 0 | pad with 0 instead of space for widths larger than value
# | <[({\| | defines an enclosing pair <> [] () {} or \| \| when used with a container type
#
#
# ### Additional parameters for containers; Array and Hash
#
# For containers (Array and Hash), the format is specified by a hash where the following keys can be set:
# * `'format'` - the format specifier for the container itself
# * `'separator'` - the separator string to use between elements, should not contain padding space at the end
# * `'separator2'` - the separator string to use between association of hash entries key/value
# * `'string_formats'´ - a map of type to format for elements contained in the container
#
# Note that the top level format applies to Array and Hash objects contained/nested in an Array or a Hash.
#
# Given format mappings are merged with (default) formats and a format specified for a narrower type
# wins over a broader.
#
# @param mode [String, Symbol] :strict or :extended (or :default which is the same as :strict)
# @param string_formats [String, Hash] format tring, or a hash mapping type to a format string, and for Array and Hash types map to hash of details
#
def convert(value, string_formats = :default)
options = DEFAULT_STRING_FORMATS
value_type = TypeCalculator.infer_set(value)
if string_formats.is_a?(String)
# For Array and Hash, the format is given as a Hash where 'format' key is the format for the collection itself
if Puppet::Pops::Types::PArrayType::DEFAULT.assignable?(value_type)
# add the format given for the exact type
string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => string_formats } }
elsif Puppet::Pops::Types::PHashType::DEFAULT.assignable?(value_type)
# add the format given for the exact type
string_formats = { Puppet::Pops::Types::PHashType::DEFAULT => { 'format' => string_formats } }
else
# add the format given for the exact type
string_formats = { value_type => string_formats }
end
end
case string_formats
when :default
# do nothing, use default formats
when Hash
# Convert and validate user input
string_formats = validate_input(string_formats)
# Merge user given with defaults such that user options wins, merge is deep and format specific
options = Format.merge_string_formats(DEFAULT_STRING_FORMATS, string_formats)
else
raise ArgumentError, "string conversion expects a Default value or a Hash of type to format mappings, got a '#{string_formats.class}'"
end
_convert(value_type, value, options, DEFAULT_INDENTATION)
end
# # A method only used for manual debugging as the default output of the formatting rules is
# # very hard to read otherwise.
# #
# # @api private
# def dump_string_formats(f, indent = 1)
# return f.to_s unless f.is_a?(Hash)
# "{#{f.map {|k,v| "#{k.to_s} => #{dump_string_formats(v,indent+1)}"}.join(",\n#{' '*indent} ")}}"
# end
def _convert(val_type, value, format_map, indentation)
@string_visitor.visit_this_3(self, val_type, value, format_map, indentation)
end
private :_convert
def validate_input(fmt)
return nil if fmt.nil?
unless fmt.is_a?(Hash)
raise ArgumentError, "expected a hash with type to format mappings, got instance of '#{fmt.class}'"
end
fmt.each_with_object({}) do |entry, result|
key, value = entry
unless key.is_a?(Types::PAnyType)
raise ArgumentError, "top level keys in the format hash must be data types, got instance of '#{key.class}'"
end
if value.is_a?(Hash)
result[key] = validate_container_input(value)
else
result[key] = Format.new(value)
end
end
end
private :validate_input
FMT_KEYS = %w[separator separator2 format string_formats].freeze
def validate_container_input(fmt)
if (fmt.keys - FMT_KEYS).size > 0
raise ArgumentError, "only #{FMT_KEYS.map { |k| "'#{k}'" }.join(', ')} are allowed in a container format, got #{fmt}"
end
result = Format.new(fmt['format'])
result.separator = fmt['separator']
result.separator2 = fmt['separator2']
result.container_string_formats = validate_input(fmt['string_formats'])
result
end
private :validate_container_input
def string_PObjectType(val_type, val, format_map, indentation)
f = get_format(val_type, format_map)
case f.format
when :p
fmt = TypeFormatter.singleton
indentation = indentation.indenting(f.alt? || indentation.is_indenting?)
fmt = fmt.indented(indentation.level, 2) if indentation.is_indenting?
fmt.string(val)
when :s
val.to_s
when :q
val.inspect
else
raise FormatError.new('Object', f.format, 'spq')
end
end
def string_PObjectTypeExtension(val_type, val, format_map, indentation)
string_PObjectType(val_type.base_type, val, format_map, indentation)
end
def string_PRuntimeType(val_type, val, format_map, indent)
# Before giving up on this, and use a string representation of the unknown
# object, a check is made to see if the object can present itself as
# a hash or an array. If it can, then that representation is used instead.
case val
when Hash
hash = val.to_hash
# Ensure that the returned value isn't derived from Hash
return string_PHashType(val_type, hash, format_map, indent) if hash.instance_of?(Hash)
when Array
array = val.to_a
# Ensure that the returned value isn't derived from Array
return string_PArrayType(val_type, array, format_map, indent) if array.instance_of?(Array)
end
f = get_format(val_type, format_map)
case f.format
when :s
val.to_s
when :p
puppet_quote(val.to_s)
when :q
val.inspect
else
raise FormatError.new('Runtime', f.format, 'spq')
end
end
# Basically string_PAnyType converts the value to a String and then formats it according
# to the resulting type
#
# @api private
def string_PAnyType(val_type, val, format_map, _)
f = get_format(val_type, format_map)
Kernel.format(f.orig_fmt, val)
end
def string_PDefaultType(val_type, val, format_map, _)
f = get_format(val_type, format_map)
apply_string_flags(f, case f.format
when :d, :s, :p
f.alt? ? '"default"' : 'default'
when :D
f.alt? ? '"Default"' : 'Default'
else
raise FormatError.new('Default', f.format, 'dDsp')
end)
end
# @api private
def string_PUndefType(val_type, val, format_map, _)
f = get_format(val_type, format_map)
apply_string_flags(f, case f.format
when :n
f.alt? ? 'null' : 'nil'
when :u
f.alt? ? 'undefined' : 'undef'
when :d, :x, :X, :o, :b, :B, :e, :E, :f, :g, :G, :a, :A
'NaN'
when :v
'n/a'
when :V
'N/A'
when :s
f.alt? ? '""' : ''
when :p
f.alt? ? '"undef"' : 'undef'
else
raise FormatError.new('Undef', f.format,
'nudxXobBeEfgGaAvVsp')
end)
end
# @api private
def string_PBooleanType(val_type, val, format_map, indentation)
f = get_format(val_type, format_map)
case f.format
when :t
# 'true'/'false' or 't'/'f' if in alt mode
str_bool = val.to_s
apply_string_flags(f, f.alt? ? str_bool[0] : str_bool)
when :T
# 'True'/'False' or 'T'/'F' if in alt mode
str_bool = val.to_s.capitalize
apply_string_flags(f, f.alt? ? str_bool[0] : str_bool)
when :y
# 'yes'/'no' or 'y'/'n' if in alt mode
str_bool = val ? 'yes' : 'no'
apply_string_flags(f, f.alt? ? str_bool[0] : str_bool)
when :Y
# 'Yes'/'No' or 'Y'/'N' if in alt mode
str_bool = val ? 'Yes' : 'No'
apply_string_flags(f, f.alt? ? str_bool[0] : str_bool)
when :d, :x, :X, :o, :b, :B
# Boolean in numeric form, formated by integer rule
numeric_bool = val ? 1 : 0
string_formats = { Puppet::Pops::Types::PIntegerType::DEFAULT => f }
_convert(TypeCalculator.infer_set(numeric_bool), numeric_bool, string_formats, indentation)
when :e, :E, :f, :g, :G, :a, :A
# Boolean in numeric form, formated by float rule
numeric_bool = val ? 1.0 : 0.0
string_formats = { Puppet::Pops::Types::PFloatType::DEFAULT => f }
_convert(TypeCalculator.infer_set(numeric_bool), numeric_bool, string_formats, indentation)
when :s
apply_string_flags(f, val.to_s)
when :p
apply_string_flags(f, val.inspect)
else
raise FormatError.new('Boolean', f.format, 'tTyYdxXobBeEfgGaAsp')
end
end
# Performs post-processing of literals to apply width and precision flags
def apply_string_flags(f, literal_str)
if f.left || f.width || f.prec
fmt = '%'.dup
fmt << '-' if f.left
fmt << f.width.to_s if f.width
fmt << '.' << f.prec.to_s if f.prec
fmt << 's'
Kernel.format(fmt, literal_str)
else
literal_str
end
end
private :apply_string_flags
# @api private
def string_PIntegerType(val_type, val, format_map, _)
f = get_format(val_type, format_map)
case f.format
when :d, :x, :X, :o, :b, :B, :p
Kernel.format(f.orig_fmt, val)
when :e, :E, :f, :g, :G, :a, :A
Kernel.format(f.orig_fmt, val.to_f)
when :c
char = [val].pack("U")
char = f.alt? ? "\"#{char}\"" : char
Kernel.format(f.orig_fmt.tr('c', 's'), char)
when :s
fmt = f.alt? ? 'p' : 's'
int_str = Kernel.format('%d', val)
Kernel.format(f.orig_fmt.gsub('s', fmt), int_str)
else
raise FormatError.new('Integer', f.format, 'dxXobBeEfgGaAspc')
end
end
# @api private
def string_PFloatType(val_type, val, format_map, _)
f = get_format(val_type, format_map)
case f.format
when :d, :x, :X, :o, :b, :B
Kernel.format(f.orig_fmt, val.to_i)
when :e, :E, :f, :g, :G, :a, :A, :p
Kernel.format(f.orig_fmt, val)
when :s
float_str = f.alt? ? "\"#{Kernel.format('%p', val)}\"" : Kernel.format('%p', val)
Kernel.format(f.orig_fmt, float_str)
else
raise FormatError.new('Float', f.format, 'dxXobBeEfgGaAsp')
end
end
# @api private
def string_PBinaryType(val_type, val, format_map, _)
f = get_format(val_type, format_map)
substitute = f.alt? ? 'p' : 's'
case f.format
when :s
val_to_convert = val.binary_buffer
if !f.alt?
# Assume it is valid UTF-8
val_to_convert = val_to_convert.dup.force_encoding('UTF-8')
# If it isn't
unless val_to_convert.valid_encoding?
# try to convert and fail with details about what is wrong
val_to_convert = val.binary_buffer.encode('UTF-8')
end
else
val_to_convert = val.binary_buffer
end
Kernel.format(f.orig_fmt.gsub('s', substitute), val_to_convert)
when :p
# width & precision applied to string, not the name of the type
"Binary(\"#{Kernel.format(f.orig_fmt.tr('p', 's'), val.to_s)}\")"
when :b
Kernel.format(f.orig_fmt.gsub('b', substitute), val.relaxed_to_s)
when :B
Kernel.format(f.orig_fmt.gsub('B', substitute), val.to_s)
when :u
Kernel.format(f.orig_fmt.gsub('u', substitute), val.urlsafe_to_s)
when :t
# Output as the type without any data
Kernel.format(f.orig_fmt.gsub('t', substitute), 'Binary')
when :T
# Output as the type without any data in all caps
Kernel.format(f.orig_fmt.gsub('T', substitute), 'BINARY')
else
raise FormatError.new('Binary', f.format, 'bButTsp')
end
end
# @api private
def string_PStringType(val_type, val, format_map, _)
f = get_format(val_type, format_map)
case f.format
when :s
Kernel.format(f.orig_fmt, val)
when :p
apply_string_flags(f, puppet_quote(val, f.alt?))
when :c
c_val = val.capitalize
f.alt? ? apply_string_flags(f, puppet_quote(c_val)) : Kernel.format(f.orig_fmt.tr('c', 's'), c_val)
when :C
c_val = val.split('::').map(&:capitalize).join('::')
f.alt? ? apply_string_flags(f, puppet_quote(c_val)) : Kernel.format(f.orig_fmt.tr('C', 's'), c_val)
when :u
c_val = val.upcase
f.alt? ? apply_string_flags(f, puppet_quote(c_val)) : Kernel.format(f.orig_fmt.tr('u', 's'), c_val)
when :d
c_val = val.downcase
f.alt? ? apply_string_flags(f, puppet_quote(c_val)) : Kernel.format(f.orig_fmt.tr('d', 's'), c_val)
when :t # trim
c_val = val.strip
f.alt? ? apply_string_flags(f, puppet_quote(c_val)) : Kernel.format(f.orig_fmt.tr('t', 's'), c_val)
else
raise FormatError.new('String', f.format, 'cCudspt')
end
end
# Performs a '%p' formatting of the given _str_ such that the output conforms to Puppet syntax. An ascii string
# without control characters, dollar, single-qoute, or backslash, will be quoted using single quotes. All other
# strings will be quoted using double quotes.
#
# @param [String] str the string that should be formatted
# @param [Boolean] enforce_double_quotes if true the result will be double quoted (even if single quotes would be possible)
# @return [String] the formatted string
#
# @api public
def puppet_quote(str, enforce_double_quotes = false)
if enforce_double_quotes
return puppet_double_quote(str)
end
# Assume that the string can be single quoted
bld = "'".dup
bld.force_encoding(str.encoding)
escaped = false
str.each_codepoint do |codepoint|
# Control characters and non-ascii characters cannot be present in a single quoted string
return puppet_double_quote(str) if codepoint < 0x20
if escaped
bld << 0x5c << codepoint
escaped = false
elsif codepoint == 0x27
bld << 0x5c << codepoint
elsif codepoint == 0x5c
escaped = true
elsif codepoint <= 0x7f
bld << codepoint
else
bld << [codepoint].pack('U')
end
end
# If string ended with a backslash, then that backslash must be escaped
bld << 0x5c if escaped
bld << "'"
bld
end
def puppet_double_quote(str)
bld = '"'.dup
str.each_codepoint do |codepoint|
case codepoint
when 0x09
bld << '\\t'
when 0x0a
bld << '\\n'
when 0x0d
bld << '\\r'
when 0x22
bld << '\\"'
when 0x24
bld << '\\$'
when 0x5c
bld << '\\\\'
else
if codepoint < 0x20
bld << sprintf('\\u{%X}', codepoint)
elsif codepoint <= 0x7f
bld << codepoint
else
bld << [codepoint].pack('U')
end
end
end
bld << '"'
bld
end
# @api private
def string_PRegexpType(val_type, val, format_map, _)
f = get_format(val_type, format_map)
case f.format
when :p
str_regexp = PRegexpType.regexp_to_s_with_delimiters(val)
f.orig_fmt == '%p' ? str_regexp : Kernel.format(f.orig_fmt.tr('p', 's'), str_regexp)
when :s
str_regexp = PRegexpType.regexp_to_s(val)
str_regexp = puppet_quote(str_regexp) if f.alt?
f.orig_fmt == '%s' ? str_regexp : Kernel.format(f.orig_fmt, str_regexp)
else
raise FormatError.new('Regexp', f.format, 'sp')
end
end
def string_PArrayType(val_type, val, format_map, indentation)
format = get_format(val_type, format_map)
sep = format.separator || DEFAULT_ARRAY_FORMAT.separator
string_formats = format.container_string_formats || DEFAULT_CONTAINER_FORMATS
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/p_uri_type.rb | lib/puppet/pops/types/p_uri_type.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
class PURIType < PAnyType
# Tell evaluator that an members of instances of this type can be invoked using dot notation
include TypeWithMembers
SCHEME = 'scheme'
USERINFO = 'userinfo'
HOST = 'host'
PORT = 'port'
PATH = 'path'
QUERY = 'query'
FRAGMENT = 'fragment'
OPAQUE = 'opaque'
URI_MEMBERS = {
SCHEME => AttrReader.new(SCHEME),
USERINFO => AttrReader.new(USERINFO),
HOST => AttrReader.new(HOST),
PORT => AttrReader.new(PORT),
PATH => AttrReader.new(PATH),
QUERY => AttrReader.new(QUERY),
FRAGMENT => AttrReader.new(FRAGMENT),
OPAQUE => AttrReader.new(OPAQUE),
}
TYPE_URI_INIT_HASH = TypeFactory.struct(
TypeFactory.optional(SCHEME) => PStringType::NON_EMPTY,
TypeFactory.optional(USERINFO) => PStringType::NON_EMPTY,
TypeFactory.optional(HOST) => PStringType::NON_EMPTY,
TypeFactory.optional(PORT) => PIntegerType.new(0),
TypeFactory.optional(PATH) => PStringType::NON_EMPTY,
TypeFactory.optional(QUERY) => PStringType::NON_EMPTY,
TypeFactory.optional(FRAGMENT) => PStringType::NON_EMPTY,
TypeFactory.optional(OPAQUE) => PStringType::NON_EMPTY
)
TYPE_STRING_PARAM =
TypeFactory
.optional(PVariantType
.new([
PStringType::NON_EMPTY,
PRegexpType::DEFAULT,
TypeFactory.type_type(PPatternType::DEFAULT),
TypeFactory.type_type(PEnumType::DEFAULT),
TypeFactory.type_type(PNotUndefType::DEFAULT),
TypeFactory.type_type(PUndefType::DEFAULT)
]))
TYPE_INTEGER_PARAM =
TypeFactory
.optional(PVariantType
.new([
PIntegerType.new(0),
TypeFactory.type_type(PNotUndefType::DEFAULT),
TypeFactory.type_type(PUndefType::DEFAULT)
]))
TYPE_URI_PARAM_HASH_TYPE = TypeFactory.struct(
TypeFactory.optional(SCHEME) => TYPE_STRING_PARAM,
TypeFactory.optional(USERINFO) => TYPE_STRING_PARAM,
TypeFactory.optional(HOST) => TYPE_STRING_PARAM,
TypeFactory.optional(PORT) => TYPE_INTEGER_PARAM,
TypeFactory.optional(PATH) => TYPE_STRING_PARAM,
TypeFactory.optional(QUERY) => TYPE_STRING_PARAM,
TypeFactory.optional(FRAGMENT) => TYPE_STRING_PARAM,
TypeFactory.optional(OPAQUE) => TYPE_STRING_PARAM
)
TYPE_URI_PARAM_TYPE = PVariantType.new([PStringType::NON_EMPTY, TYPE_URI_PARAM_HASH_TYPE])
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'AnyType',
{
'parameters' => { KEY_TYPE => TypeFactory.optional(TYPE_URI_PARAM_TYPE), KEY_VALUE => nil }
})
end
def self.new_function(type)
@new_function ||= Puppet::Functions.create_loaded_function(:new_error, type.loader) do
dispatch :create do
param 'String[1]', :uri
end
dispatch :from_hash do
param TYPE_URI_INIT_HASH, :hash
end
def create(uri)
URI.parse(uri)
end
def from_hash(init_hash)
sym_hash = {}
init_hash.each_pair { |k, v| sym_hash[k.to_sym] = v }
scheme = sym_hash[:scheme]
scheme_class = scheme.nil? ? URI::Generic : (URI.scheme_list[scheme.upcase] || URI::Generic)
scheme_class.build(sym_hash)
end
end
end
attr_reader :parameters
def initialize(parameters = nil)
case parameters
when String
parameters = TypeAsserter.assert_instance_of('URI-Type parameter', Pcore::TYPE_URI, parameters, true)
@parameters = uri_to_hash(URI.parse(parameters))
when URI
@parameters = uri_to_hash(parameters)
when Hash
params = TypeAsserter.assert_instance_of('URI-Type parameter', TYPE_URI_PARAM_TYPE, parameters, true)
@parameters = params.empty? ? nil : params
end
end
def eql?(o)
self.class == o.class && @parameters == o.parameters
end
def ==(o)
eql?(o)
end
def [](key)
URI_MEMBERS[key]
end
def generalize
DEFAULT
end
def hash
self.class.hash ^ @parameters.hash
end
def instance?(o, guard = nil)
return false unless o.is_a?(URI)
return true if @parameters.nil?
eval = Parser::EvaluatingParser.singleton.evaluator
@parameters.keys.all? { |pn| eval.match?(o.send(pn), @parameters[pn]) }
end
def roundtrip_with_string?
true
end
def _pcore_init_hash
@parameters == nil? ? EMPTY_HASH : { 'parameters' => @parameters }
end
protected
def _assignable?(o, guard = nil)
return false unless o.instance_of?(self.class)
return true if @parameters.nil?
o_params = o.parameters || EMPTY_HASH
eval = Parser::EvaluatingParser.singleton.evaluator
@parameters.keys.all? do |pn|
if o_params.include?(pn)
a = o_params[pn]
b = @parameters[pn]
eval.match?(a, b) || a.is_a?(PAnyType) && b.is_a?(PAnyType) && b.assignable?(a)
else
false
end
end
end
private
def uri_to_hash(uri)
result = {}
scheme = uri.scheme
unless scheme.nil?
scheme = scheme.downcase
result[SCHEME] = scheme
end
result[USERINFO] = uri.userinfo unless uri.userinfo.nil?
result[HOST] = uri.host.downcase unless uri.host.nil? || uri.host.empty?
result[PORT] = uri.port.to_s unless uri.port.nil? || uri.port == 80 && 'http' == scheme || uri.port == 443 && 'https' == scheme
result[PATH] = uri.path unless uri.path.nil? || uri.path.empty?
result[QUERY] = uri.query unless uri.query.nil?
result[FRAGMENT] = uri.fragment unless uri.fragment.nil?
result[OPAQUE] = uri.opaque unless uri.opaque.nil?
result.empty? ? nil : result
end
DEFAULT = PURIType.new(nil)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/annotation.rb | lib/puppet/pops/types/annotation.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
# Pcore variant of the Adaptable::Adapter. Uses a Pcore Object type instead of a Class
class Annotation < Adaptable::Adapter
include Types::PuppetObject
CLEAR = 'clear'
# Register the Annotation type. This is the type that all custom Annotations will inherit from.
def self.register_ptype(loader, ir)
@type = Pcore.create_object_type(loader, ir, self, 'Annotation', nil, EMPTY_HASH)
end
def self._pcore_type
@type
end
# Finds an existing annotation for the given object and returns it.
# If no annotation was found, and a block is given, a new annotation is created from the
# initializer hash that must be returned from the block.
# If no annotation was found and no block is given, this method returns `nil`
#
# @param o [Object] object to annotate
# @param block [Proc] optional, evaluated when a new annotation must be created. Should return the init hash
# @return [Annotation<self>] an annotation of the same class as the receiver of the call
#
def self.annotate(o)
adapter = get(o)
if adapter.nil?
if o.is_a?(Annotatable)
init_hash = o.annotations[_pcore_type]
init_hash = yield if init_hash.nil? && block_given?
elsif block_given?
init_hash = yield
end
adapter = associate_adapter(_pcore_type.from_hash(init_hash), o) unless init_hash.nil?
end
adapter
end
# Forces the creation or removal of an annotation of this type.
# If `init_hash` is a hash, a new annotation is created and returned
# If `init_hash` is `nil`, then the annotation is cleared and the previous annotation is returned.
#
# @param o [Object] object to annotate
# @param init_hash [Hash{String,Object},nil] the initializer for the annotation or `nil` to clear the annotation
# @return [Annotation<self>] an annotation of the same class as the receiver of the call
#
def self.annotate_new(o, init_hash)
if o.is_a?(Annotatable) && o.annotations.include?(_pcore_type)
# Prevent clear or redefine of annotations declared on type
action = init_hash == CLEAR ? 'clear' : 'redefine'
raise ArgumentError, "attempt to #{action} #{type_name} annotation declared on #{o.label}"
end
if init_hash == CLEAR
clear(o)
else
associate_adapter(_pcore_type.from_hash(init_hash), o)
end
end
# Uses name of type instead of name of the class (the class is likely dynamically generated and as such,
# has no name)
# @return [String] the name of the type
def self.type_name
_pcore_type.name
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/p_object_type.rb | lib/puppet/pops/types/p_object_type.rb | # frozen_string_literal: true
require_relative 'ruby_generator'
require_relative 'type_with_members'
module Puppet::Pops
module Types
KEY_ATTRIBUTES = 'attributes'
KEY_CHECKS = 'checks'
KEY_CONSTANTS = 'constants'
KEY_EQUALITY = 'equality'
KEY_EQUALITY_INCLUDE_TYPE = 'equality_include_type'
KEY_FINAL = 'final'
KEY_FUNCTIONS = 'functions'
KEY_KIND = 'kind'
KEY_OVERRIDE = 'override'
KEY_PARENT = 'parent'
KEY_TYPE_PARAMETERS = 'type_parameters'
# @api public
class PObjectType < PMetaType
include TypeWithMembers
ATTRIBUTE_KIND_CONSTANT = 'constant'
ATTRIBUTE_KIND_DERIVED = 'derived'
ATTRIBUTE_KIND_GIVEN_OR_DERIVED = 'given_or_derived'
ATTRIBUTE_KIND_REFERENCE = 'reference'
TYPE_ATTRIBUTE_KIND = TypeFactory.enum(ATTRIBUTE_KIND_CONSTANT, ATTRIBUTE_KIND_DERIVED, ATTRIBUTE_KIND_GIVEN_OR_DERIVED, ATTRIBUTE_KIND_REFERENCE)
TYPE_OBJECT_NAME = Pcore::TYPE_QUALIFIED_REFERENCE
TYPE_ATTRIBUTE =
TypeFactory
.struct({
KEY_TYPE => PTypeType::DEFAULT,
TypeFactory.optional(KEY_FINAL) => PBooleanType::DEFAULT,
TypeFactory.optional(KEY_OVERRIDE) => PBooleanType::DEFAULT,
TypeFactory.optional(KEY_KIND) => TYPE_ATTRIBUTE_KIND,
KEY_VALUE => PAnyType::DEFAULT,
TypeFactory.optional(KEY_ANNOTATIONS) => TYPE_ANNOTATIONS
})
TYPE_PARAMETER =
TypeFactory
.struct({
KEY_TYPE => PTypeType::DEFAULT,
TypeFactory.optional(KEY_ANNOTATIONS) => TYPE_ANNOTATIONS
})
TYPE_CONSTANTS = TypeFactory.hash_kv(Pcore::TYPE_MEMBER_NAME, PAnyType::DEFAULT)
TYPE_ATTRIBUTES = TypeFactory.hash_kv(Pcore::TYPE_MEMBER_NAME, TypeFactory.not_undef)
TYPE_PARAMETERS = TypeFactory.hash_kv(Pcore::TYPE_MEMBER_NAME, TypeFactory.not_undef)
TYPE_ATTRIBUTE_CALLABLE = TypeFactory.callable(0, 0)
TYPE_FUNCTION_TYPE = PTypeType.new(PCallableType::DEFAULT)
TYPE_FUNCTION =
TypeFactory
.struct({
KEY_TYPE => TYPE_FUNCTION_TYPE,
TypeFactory.optional(KEY_FINAL) => PBooleanType::DEFAULT,
TypeFactory.optional(KEY_OVERRIDE) => PBooleanType::DEFAULT,
TypeFactory.optional(KEY_ANNOTATIONS) => TYPE_ANNOTATIONS
})
TYPE_FUNCTIONS = TypeFactory.hash_kv(PVariantType.new([Pcore::TYPE_MEMBER_NAME, PStringType.new('[]')]), TypeFactory.not_undef)
TYPE_EQUALITY = TypeFactory.variant(Pcore::TYPE_MEMBER_NAME, TypeFactory.array_of(Pcore::TYPE_MEMBER_NAME))
TYPE_CHECKS = PAnyType::DEFAULT # TBD
TYPE_OBJECT_I12N =
TypeFactory
.struct({
TypeFactory.optional(KEY_NAME) => TYPE_OBJECT_NAME,
TypeFactory.optional(KEY_PARENT) => PTypeType::DEFAULT,
TypeFactory.optional(KEY_TYPE_PARAMETERS) => TYPE_PARAMETERS,
TypeFactory.optional(KEY_ATTRIBUTES) => TYPE_ATTRIBUTES,
TypeFactory.optional(KEY_CONSTANTS) => TYPE_CONSTANTS,
TypeFactory.optional(KEY_FUNCTIONS) => TYPE_FUNCTIONS,
TypeFactory.optional(KEY_EQUALITY) => TYPE_EQUALITY,
TypeFactory.optional(KEY_EQUALITY_INCLUDE_TYPE) => PBooleanType::DEFAULT,
TypeFactory.optional(KEY_CHECKS) => TYPE_CHECKS,
TypeFactory.optional(KEY_ANNOTATIONS) => TYPE_ANNOTATIONS
})
def self.register_ptype(loader, ir)
type = create_ptype(loader, ir, 'AnyType', '_pcore_init_hash' => TYPE_OBJECT_I12N)
# Now, when the Object type exists, add annotations with keys derived from Annotation and freeze the types.
annotations = TypeFactory.optional(PHashType.new(PTypeType.new(Annotation._pcore_type), TypeFactory.hash_kv(Pcore::TYPE_MEMBER_NAME, PAnyType::DEFAULT)))
TYPE_ATTRIBUTE.hashed_elements[KEY_ANNOTATIONS].replace_value_type(annotations)
TYPE_FUNCTION.hashed_elements[KEY_ANNOTATIONS].replace_value_type(annotations)
TYPE_OBJECT_I12N.hashed_elements[KEY_ANNOTATIONS].replace_value_type(annotations)
PTypeSetType::TYPE_TYPESET_I12N.hashed_elements[KEY_ANNOTATIONS].replace_value_type(annotations)
PTypeSetType::TYPE_TYPE_REFERENCE_I12N.hashed_elements[KEY_ANNOTATIONS].replace_value_type(annotations)
type
end
# @abstract Encapsulates behavior common to {PAttribute} and {PFunction}
# @api public
class PAnnotatedMember
include Annotatable
include InvocableMember
# @return [PObjectType] the object type containing this member
# @api public
attr_reader :container
# @return [String] the name of this member
# @api public
attr_reader :name
# @return [PAnyType] the type of this member
# @api public
attr_reader :type
# @param name [String] The name of the member
# @param container [PObjectType] The containing object type
# @param init_hash [Hash{String=>Object}] Hash containing feature options
# @option init_hash [PAnyType] 'type' The member type (required)
# @option init_hash [Boolean] 'override' `true` if this feature must override an inherited feature. Default is `false`.
# @option init_hash [Boolean] 'final' `true` if this feature cannot be overridden. Default is `false`.
# @option init_hash [Hash{PTypeType => Hash}] 'annotations' Annotations hash. Default is `nil`.
# @api public
def initialize(name, container, init_hash)
@name = name
@container = container
@type = init_hash[KEY_TYPE]
@override = init_hash[KEY_OVERRIDE]
@override = false if @override.nil?
@final = init_hash[KEY_FINAL]
@final = false if @final.nil?
init_annotatable(init_hash)
end
# Delegates to the contained type
# @param visitor [TypeAcceptor] the visitor
# @param guard [RecursionGuard] guard against recursion. Only used by internal calls
# @api public
def accept(visitor, guard)
annotatable_accept(visitor, guard)
@type.accept(visitor, guard)
end
# Checks if the this _member_ overrides an inherited member, and if so, that this member is declared with override = true and that
# the inherited member accepts to be overridden by this member.
#
# @param parent_members [Hash{String=>PAnnotatedMember}] the hash of inherited members
# @return [PAnnotatedMember] this instance
# @raises [Puppet::ParseError] if the assertion fails
# @api private
def assert_override(parent_members)
parent_member = parent_members[@name]
if parent_member.nil?
if @override
raise Puppet::ParseError, _("expected %{label} to override an inherited %{feature_type}, but no such %{feature_type} was found") %
{ label: label, feature_type: feature_type }
end
self
else
parent_member.assert_can_be_overridden(self)
end
end
# Checks if the given _member_ can override this member.
#
# @param member [PAnnotatedMember] the overriding member
# @return [PAnnotatedMember] its argument
# @raises [Puppet::ParseError] if the assertion fails
# @api private
def assert_can_be_overridden(member)
unless instance_of?(member.class)
raise Puppet::ParseError, _("%{member} attempts to override %{label}") % { member: member.label, label: label }
end
if @final && !(constant? && member.constant?)
raise Puppet::ParseError, _("%{member} attempts to override final %{label}") % { member: member.label, label: label }
end
unless member.override?
# TRANSLATOR 'override => true' is a puppet syntax and should not be translated
raise Puppet::ParseError, _("%{member} attempts to override %{label} without having override => true") % { member: member.label, label: label }
end
unless @type.assignable?(member.type)
raise Puppet::ParseError, _("%{member} attempts to override %{label} with a type that does not match") % { member: member.label, label: label }
end
member
end
def constant?
false
end
# @return [Boolean] `true` if this feature cannot be overridden
# @api public
def final?
@final
end
# @return [Boolean] `true` if this feature must override an inherited feature
# @api public
def override?
@override
end
# @api public
def hash
@name.hash ^ @type.hash
end
# @api public
def eql?(o)
self.class == o.class && @name == o.name && @type == o.type && @override == o.override? && @final == o.final?
end
# @api public
def ==(o)
eql?(o)
end
# Returns the member as a hash suitable as an argument for constructor. Name is excluded
# @return [Hash{String=>Object}] the initialization hash
# @api private
def _pcore_init_hash
hash = { KEY_TYPE => @type }
hash[KEY_FINAL] = true if @final
hash[KEY_OVERRIDE] = true if @override
hash[KEY_ANNOTATIONS] = @annotations unless @annotations.nil?
hash
end
# @api private
def feature_type
self.class.feature_type
end
# @api private
def label
self.class.label(@container, @name)
end
# Performs type checking of arguments and invokes the method that corresponds to this
# method. The result of the invocation is returned
#
# @param receiver [Object] The receiver of the call
# @param scope [Puppet::Parser::Scope] The caller scope
# @param args [Array] Array of arguments.
# @return [Object] The result returned by the member function or attribute
#
# @api private
def invoke(receiver, scope, args, &block)
@dispatch ||= create_dispatch(receiver)
args_type = TypeCalculator.infer_set(block_given? ? args + [block] : args)
found = @dispatch.find { |d| d.type.callable?(args_type) }
raise ArgumentError, TypeMismatchDescriber.describe_signatures(label, @dispatch, args_type) if found.nil?
found.invoke(receiver, scope, args, &block)
end
# @api private
def create_dispatch(instance)
# TODO: Assumes Ruby implementation for now
if callable_type.is_a?(PVariantType)
callable_type.types.map do |ct|
Functions::Dispatch.new(ct, RubyGenerator.protect_reserved_name(name), [], false, ct.block_type.nil? ? nil : 'block')
end
else
[Functions::Dispatch.new(callable_type, RubyGenerator.protect_reserved_name(name), [], false, callable_type.block_type.nil? ? nil : 'block')]
end
end
# @api private
def self.feature_type
raise NotImplementedError, "'#{self.class.name}' should implement #feature_type"
end
def self.label(container, name)
"#{feature_type} #{container.label}[#{name}]"
end
end
# Describes a named Attribute in an Object type
# @api public
class PAttribute < PAnnotatedMember
# @return [String,nil] The attribute kind as defined by #TYPE_ATTRIBUTE_KIND, or `nil`
attr_reader :kind
# @param name [String] The name of the attribute
# @param container [PObjectType] The containing object type
# @param init_hash [Hash{String=>Object}] Hash containing attribute options
# @option init_hash [PAnyType] 'type' The attribute type (required)
# @option init_hash [Object] 'value' The default value, must be an instanceof the given `type` (optional)
# @option init_hash [String] 'kind' The attribute kind, matching #TYPE_ATTRIBUTE_KIND
# @api public
def initialize(name, container, init_hash)
super(name, container, TypeAsserter.assert_instance_of(nil, TYPE_ATTRIBUTE, init_hash) { "initializer for #{self.class.label(container, name)}" })
if name == Serialization::PCORE_TYPE_KEY || name == Serialization::PCORE_VALUE_KEY
raise Puppet::ParseError, _("The attribute '%{name}' is reserved and cannot be used") % { name: name }
end
@kind = init_hash[KEY_KIND]
if @kind == ATTRIBUTE_KIND_CONSTANT # final is implied
if init_hash.include?(KEY_FINAL) && !@final
# TRANSLATOR 'final => false' is puppet syntax and should not be translated
raise Puppet::ParseError, _("%{label} of kind 'constant' cannot be combined with final => false") % { label: label }
end
@final = true
end
if init_hash.include?(KEY_VALUE)
if @kind == ATTRIBUTE_KIND_DERIVED || @kind == ATTRIBUTE_KIND_GIVEN_OR_DERIVED
raise Puppet::ParseError, _("%{label} of kind '%{kind}' cannot be combined with an attribute value") % { label: label, kind: @kind }
end
v = init_hash[KEY_VALUE]
@value = v == :default ? v : TypeAsserter.assert_instance_of(nil, type, v) { "#{label} #{KEY_VALUE}" }
else
raise Puppet::ParseError, _("%{label} of kind 'constant' requires a value") % { label: label } if @kind == ATTRIBUTE_KIND_CONSTANT
@value = :undef # Not to be confused with nil or :default
end
end
def callable_type
TYPE_ATTRIBUTE_CALLABLE
end
# @api public
def eql?(o)
super && @kind == o.kind && @value == (o.value? ? o.value : :undef)
end
# Returns the member as a hash suitable as an argument for constructor. Name is excluded
# @return [Hash{String=>Object}] the hash
# @api private
def _pcore_init_hash
hash = super
unless @kind.nil?
hash[KEY_KIND] = @kind
hash.delete(KEY_FINAL) if @kind == ATTRIBUTE_KIND_CONSTANT # final is implied
end
hash[KEY_VALUE] = @value unless @value == :undef
hash
end
def constant?
@kind == ATTRIBUTE_KIND_CONSTANT
end
# @return [Booelan] true if the given value equals the default value for this attribute
def default_value?(value)
@value == value
end
# @return [Boolean] `true` if a value has been defined for this attribute.
def value?
@value != :undef
end
# Returns the value of this attribute, or raises an error if no value has been defined. Raising an error
# is necessary since a defined value may be `nil`.
#
# @return [Object] the value that has been defined for this attribute.
# @raise [Puppet::Error] if no value has been defined
# @api public
def value
# An error must be raised here since `nil` is a valid value and it would be bad to leak the :undef symbol
raise Puppet::Error, "#{label} has no value" if @value == :undef
@value
end
# @api private
def self.feature_type
'attribute'
end
end
class PTypeParameter < PAttribute
# @return [Hash{String=>Object}] the hash
# @api private
def _pcore_init_hash
hash = super
hash[KEY_TYPE] = hash[KEY_TYPE].type
hash.delete(KEY_VALUE) if hash.include?(KEY_VALUE) && hash[KEY_VALUE].nil?
hash
end
# @api private
def self.feature_type
'type_parameter'
end
end
# Describes a named Function in an Object type
# @api public
class PFunction < PAnnotatedMember
# @param name [String] The name of the attribute
# @param container [PObjectType] The containing object type
# @param init_hash [Hash{String=>Object}] Hash containing function options
# @api public
def initialize(name, container, init_hash)
super(name, container, TypeAsserter.assert_instance_of(["initializer for function '%s'", name], TYPE_FUNCTION, init_hash))
end
def callable_type
type
end
# @api private
def self.feature_type
'function'
end
end
attr_reader :name
attr_reader :parent
attr_reader :equality
attr_reader :checks
attr_reader :annotations
# Initialize an Object Type instance. The initialization will use either a name and an initialization
# hash expression, or a fully resolved initialization hash.
#
# @overload initialize(name, init_hash_expression)
# Used when the Object type is loaded using a type alias expression. When that happens, it is important that
# the actual resolution of the expression is deferred until all definitions have been made known to the current
# loader. The object will then be resolved when it is loaded by the {TypeParser}. "resolved" here, means that
# the hash expression is fully resolved, and then passed to the {#_pcore_init_from_hash} method.
# @param name [String] The name of the object
# @param init_hash_expression [Model::LiteralHash] The hash describing the Object features
#
# @overload initialize(init_hash)
# Used when the object is created by the {TypeFactory}. The init_hash must be fully resolved.
# @param _pcore_init_hash [Hash{String=>Object}] The hash describing the Object features
# @param loader [Loaders::Loader,nil] the loader that loaded the type
#
# @api private
def initialize(_pcore_init_hash, init_hash_expression = nil) # rubocop:disable Lint/UnderscorePrefixedVariableName
if _pcore_init_hash.is_a?(Hash)
_pcore_init_from_hash(_pcore_init_hash)
@loader = init_hash_expression unless init_hash_expression.nil?
else
@type_parameters = EMPTY_HASH
@attributes = EMPTY_HASH
@functions = EMPTY_HASH
@name = TypeAsserter.assert_instance_of('object name', TYPE_OBJECT_NAME, _pcore_init_hash)
@init_hash_expression = init_hash_expression
end
end
def instance?(o, guard = nil)
if o.is_a?(PuppetObject)
assignable?(o._pcore_type, guard)
else
name = o.class.name
return false if name.nil? # anonymous class that doesn't implement PuppetObject is not an instance
ir = Loaders.implementation_registry
type = ir.nil? ? nil : ir.type_for_module(name)
!type.nil? && assignable?(type, guard)
end
end
# @api private
def new_function
@new_function ||= create_new_function
end
# Assign a new instance reader to this type
# @param [Serialization::InstanceReader] reader the reader to assign
# @api private
def reader=(reader)
@reader = reader
end
# Assign a new instance write to this type
# @param [Serialization::InstanceWriter] the writer to assign
# @api private
def writer=(writer)
@writer = writer
end
# Read an instance of this type from a deserializer
# @param [Integer] value_count the number attributes needed to create the instance
# @param [Serialization::Deserializer] deserializer the deserializer to read from
# @return [Object] the created instance
# @api private
def read(value_count, deserializer)
reader.read(self, implementation_class, value_count, deserializer)
end
# Write an instance of this type using a serializer
# @param [Object] value the instance to write
# @param [Serialization::Serializer] the serializer to write to
# @api private
def write(value, serializer)
writer.write(self, value, serializer)
end
# @api private
def create_new_function
impl_class = implementation_class
return impl_class.create_new_function(self) if impl_class.respond_to?(:create_new_function)
(param_names, param_types, required_param_count) = parameter_info(impl_class)
# Create the callable with a size that reflects the required and optional parameters
create_type = TypeFactory.callable(*param_types, required_param_count, param_names.size)
from_hash_type = TypeFactory.callable(init_hash_type, 1, 1)
# Create and return a #new_XXX function where the dispatchers are added programmatically.
Puppet::Functions.create_loaded_function(:"new_#{name}", loader) do
# The class that creates new instances must be available to the constructor methods
# and is therefore declared as a variable and accessor on the class that represents
# this added function.
@impl_class = impl_class
def self.impl_class
@impl_class
end
# It's recommended that an implementor of an Object type provides the method #from_asserted_hash.
# This method should accept a hash and assume that type assertion has been made already (it is made
# by the dispatch added here).
if impl_class.respond_to?(:from_asserted_hash)
dispatcher.add(Functions::Dispatch.new(from_hash_type, :from_hash, ['hash']))
def from_hash(hash)
self.class.impl_class.from_asserted_hash(hash)
end
end
# Add the dispatch that uses the standard #from_asserted_args or #new method on the class. It's assumed that the
# method performs no assertions.
dispatcher.add(Functions::Dispatch.new(create_type, :create, param_names))
if impl_class.respond_to?(:from_asserted_args)
def create(*args)
self.class.impl_class.from_asserted_args(*args)
end
else
def create(*args)
self.class.impl_class.new(*args)
end
end
end
end
# @api private
def implementation_class(create = true)
if @implementation_class.nil? && create
ir = Loaders.implementation_registry
class_name = ir.nil? ? nil : ir.module_name_for_type(self)
if class_name.nil?
# Use generator to create a default implementation
@implementation_class = RubyGenerator.new.create_class(self)
@implementation_class.class_eval(&@implementation_override) if instance_variable_defined?(:@implementation_override)
else
# Can the mapping be loaded?
@implementation_class = ClassLoader.provide(class_name)
raise Puppet::Error, "Unable to load class #{class_name}" if @implementation_class.nil?
unless @implementation_class < PuppetObject || @implementation_class.respond_to?(:ecore)
raise Puppet::Error, "Unable to create an instance of #{name}. #{class_name} does not include module #{PuppetObject.name}"
end
end
end
@implementation_class
end
# @api private
def implementation_class=(cls)
raise ArgumentError, "attempt to redefine implementation class for #{label}" unless @implementation_class.nil?
@implementation_class = cls
end
# The block passed to this method will be passed in a call to `#class_eval` on the dynamically generated
# class for this data type. It's indended use is to complement or redefine the generated methods and
# attribute readers.
#
# The method is normally called with the block passed to `#implementation` when a data type is defined using
# {Puppet::DataTypes::create_type}.
#
# @api private
def implementation_override=(block)
if !@implementation_class.nil? || instance_variable_defined?(:@implementation_override)
raise ArgumentError, "attempt to redefine implementation override for #{label}"
end
@implementation_override = block
end
def extract_init_hash(o)
return o._pcore_init_hash if o.respond_to?(:_pcore_init_hash)
result = {}
pic = parameter_info(o.class)
attrs = attributes(true)
pic[0].each do |name|
v = o.send(name)
result[name] = v unless attrs[name].default_value?(v)
end
result
end
# @api private
# @return [(Array<String>, Array<PAnyType>, Integer)] array of parameter names, array of parameter types, and a count reflecting the required number of parameters
def parameter_info(impl_class)
# Create a types and a names array where optional entries ends up last
@parameter_info ||= {}
pic = @parameter_info[impl_class]
return pic if pic
opt_types = []
opt_names = []
non_opt_types = []
non_opt_names = []
init_hash_type.elements.each do |se|
if se.key_type.is_a?(POptionalType)
opt_names << se.name
opt_types << se.value_type
else
non_opt_names << se.name
non_opt_types << se.value_type
end
end
param_names = non_opt_names + opt_names
param_types = non_opt_types + opt_types
param_count = param_names.size
init = impl_class.respond_to?(:from_asserted_args) ? impl_class.method(:from_asserted_args) : impl_class.instance_method(:initialize)
init_non_opt_count = 0
init_param_names = init.parameters.map do |p|
init_non_opt_count += 1 if :req == p[0]
n = p[1].to_s
r = RubyGenerator.unprotect_reserved_name(n)
unless r.equal?(n)
# assert that the protected name wasn't a real name (names can start with underscore)
n = r unless param_names.index(r).nil?
end
n
end
if init_param_names != param_names
if init_param_names.size < param_count || init_non_opt_count > param_count
raise Serialization::SerializationError, "Initializer for class #{impl_class.name} does not match the attributes of #{name}"
end
init_param_names = init_param_names[0, param_count] if init_param_names.size > param_count
unless init_param_names == param_names
# Reorder needed to match initialize method arguments
new_param_types = []
init_param_names.each do |ip|
index = param_names.index(ip)
if index.nil?
raise Serialization::SerializationError,
"Initializer for class #{impl_class.name} parameter '#{ip}' does not match any of the attributes of type #{name}"
end
new_param_types << param_types[index]
end
param_names = init_param_names
param_types = new_param_types
end
end
pic = [param_names.freeze, param_types.freeze, non_opt_types.size].freeze
@parameter_info[impl_class] = pic
pic
end
# @api private
def attr_reader_name(se)
if se.value_type.is_a?(PBooleanType) || se.value_type.is_a?(POptionalType) && se.value_type.type.is_a?(PBooleanType)
"#{se.name}?"
else
se.name
end
end
def self.from_hash(hash)
new(hash, nil)
end
# @api private
def _pcore_init_from_hash(init_hash)
TypeAsserter.assert_instance_of('object initializer', TYPE_OBJECT_I12N, init_hash)
@type_parameters = EMPTY_HASH
@attributes = EMPTY_HASH
@functions = EMPTY_HASH
# Name given to the loader have higher precedence than a name declared in the type
@name ||= init_hash[KEY_NAME]
@name.freeze unless @name.nil?
@parent = init_hash[KEY_PARENT]
parent_members = EMPTY_HASH
parent_type_params = EMPTY_HASH
parent_object_type = nil
unless @parent.nil?
check_self_recursion(self)
rp = resolved_parent
raise Puppet::ParseError, _("reference to unresolved type '%{name}'") % { :name => rp.type_string } if rp.is_a?(PTypeReferenceType)
if rp.is_a?(PObjectType)
parent_object_type = rp
parent_members = rp.members(true)
parent_type_params = rp.type_parameters(true)
end
end
type_parameters = init_hash[KEY_TYPE_PARAMETERS]
unless type_parameters.nil? || type_parameters.empty?
@type_parameters = {}
type_parameters.each do |key, param_spec|
param_value = :undef
if param_spec.is_a?(Hash)
param_type = param_spec[KEY_TYPE]
param_value = param_spec[KEY_VALUE] if param_spec.include?(KEY_VALUE)
else
param_type = TypeAsserter.assert_instance_of(nil, PTypeType::DEFAULT, param_spec) { "type_parameter #{label}[#{key}]" }
end
param_type = POptionalType.new(param_type) unless param_type.is_a?(POptionalType)
type_param = PTypeParameter.new(key, self, KEY_TYPE => param_type, KEY_VALUE => param_value).assert_override(parent_type_params)
@type_parameters[key] = type_param
end
end
constants = init_hash[KEY_CONSTANTS]
attr_specs = init_hash[KEY_ATTRIBUTES]
if attr_specs.nil?
attr_specs = {}
else
# attr_specs might be frozen
attr_specs = attr_specs.to_h
end
unless constants.nil? || constants.empty?
constants.each do |key, value|
if attr_specs.include?(key)
raise Puppet::ParseError, _("attribute %{label}[%{key}] is defined as both a constant and an attribute") % { label: label, key: key }
end
attr_spec = {
# Type must be generic here, or overrides would become impossible
KEY_TYPE => TypeCalculator.infer(value).generalize,
KEY_VALUE => value,
KEY_KIND => ATTRIBUTE_KIND_CONSTANT
}
# Indicate override if parent member exists. Type check etc. will take place later on.
attr_spec[KEY_OVERRIDE] = parent_members.include?(key)
attr_specs[key] = attr_spec
end
end
unless attr_specs.empty?
@attributes = attr_specs.to_h do |key, attr_spec|
unless attr_spec.is_a?(Hash)
attr_type = TypeAsserter.assert_instance_of(nil, PTypeType::DEFAULT, attr_spec) { "attribute #{label}[#{key}]" }
attr_spec = { KEY_TYPE => attr_type }
attr_spec[KEY_VALUE] = nil if attr_type.is_a?(POptionalType)
end
attr = PAttribute.new(key, self, attr_spec)
[attr.name, attr.assert_override(parent_members)]
end.freeze
end
func_specs = init_hash[KEY_FUNCTIONS]
unless func_specs.nil? || func_specs.empty?
@functions = func_specs.to_h do |key, func_spec|
func_spec = { KEY_TYPE => TypeAsserter.assert_instance_of(nil, TYPE_FUNCTION_TYPE, func_spec) { "function #{label}[#{key}]" } } unless func_spec.is_a?(Hash)
func = PFunction.new(key, self, func_spec)
name = func.name
raise Puppet::ParseError, _("%{label} conflicts with attribute with the same name") % { label: func.label } if @attributes.include?(name)
[name, func.assert_override(parent_members)]
end.freeze
end
@equality_include_type = init_hash[KEY_EQUALITY_INCLUDE_TYPE]
@equality_include_type = true if @equality_include_type.nil?
equality = init_hash[KEY_EQUALITY]
equality = [equality] if equality.is_a?(String)
if equality.is_a?(Array)
unless equality.empty?
# TRANSLATORS equality_include_type = false should not be translated
raise Puppet::ParseError, _('equality_include_type = false cannot be combined with non empty equality specification') unless @equality_include_type
parent_eq_attrs = nil
equality.each do |attr_name|
attr = parent_members[attr_name]
if attr.nil?
attr = @attributes[attr_name] || @functions[attr_name]
elsif attr.is_a?(PAttribute)
# Assert that attribute is not already include by parent equality
parent_eq_attrs ||= parent_object_type.equality_attributes
if parent_eq_attrs.include?(attr_name)
including_parent = find_equality_definer_of(attr)
raise Puppet::ParseError, _("%{label} equality is referencing %{attribute} which is included in equality of %{including_parent}") %
{ label: label, attribute: attr.label, including_parent: including_parent.label }
end
end
unless attr.is_a?(PAttribute)
if attr.nil?
raise Puppet::ParseError, _("%{label} equality is referencing non existent attribute '%{attribute}'") % { label: label, attribute: attr_name }
end
raise Puppet::ParseError, _("%{label} equality is referencing %{attribute}. Only attribute references are allowed") %
{ label: label, attribute: attr.label }
end
if attr.kind == ATTRIBUTE_KIND_CONSTANT
raise Puppet::ParseError, _("%{label} equality is referencing constant %{attribute}.") % { label: label, attribute: attr.label } + ' ' +
_("Reference to constant is not allowed in equality")
end
end
end
equality.freeze
end
@equality = equality
@checks = init_hash[KEY_CHECKS]
init_annotatable(init_hash)
end
def [](name)
member = @attributes[name] || @functions[name]
if member.nil?
rp = resolved_parent
member = rp[name] if rp.is_a?(PObjectType)
end
member
end
def accept(visitor, guard)
guarded_recursion(guard, nil) do |g|
super(visitor, g)
@parent.accept(visitor, g) unless parent.nil?
@type_parameters.values.each { |p| p.accept(visitor, g) }
@attributes.values.each { |a| a.accept(visitor, g) }
@functions.values.each { |f| f.accept(visitor, g) }
end
end
def callable_args?(callable, guard)
@parent.nil? ? false : @parent.callable_args?(callable, guard)
end
# Returns the type that a initialization hash used for creating instances of this type must conform to.
#
# @return [PStructType] the initialization hash type
# @api public
def init_hash_type
@init_hash_type ||= create_init_hash_type
end
def allocate
implementation_class.allocate
end
def create(*args)
implementation_class.create(*args)
end
def from_hash(hash)
implementation_class.from_hash(hash)
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/p_init_type.rb | lib/puppet/pops/types/p_init_type.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
# @api public
class PInitType < PTypeWithContainedType
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'AnyType',
'type' => {
KEY_TYPE => POptionalType.new(PTypeType::DEFAULT),
KEY_VALUE => nil
},
'init_args' => {
KEY_TYPE => PArrayType::DEFAULT,
KEY_VALUE => EMPTY_ARRAY
})
end
attr_reader :init_args
def initialize(type, init_args)
super(type)
@init_args = init_args.nil? ? EMPTY_ARRAY : init_args
if type.nil?
raise ArgumentError, _('Init cannot be parameterized with an undefined type and additional arguments') unless @init_args.empty?
@initialized = true
else
@initialized = false
end
end
def instance?(o, guard = nil)
really_instance?(o, guard) == 1
end
# @api private
def really_instance?(o, guard = nil)
if @type.nil?
TypeFactory.rich_data.really_instance?(o)
else
assert_initialized
guarded_recursion(guard, 0) do |g|
v = @type.really_instance?(o, g)
if v < 1
if @single_type
s = @single_type.really_instance?(o, g)
v = s if s > v
end
end
if v < 1
if @other_type
s = @other_type.really_instance?(o, g)
s = @other_type.really_instance?([o], g) if s < 0 && @has_optional_single
v = s if s > v
end
end
v
end
end
end
def eql?(o)
super && @init_args == o.init_args
end
def hash
super ^ @init_args.hash
end
def new_function
return super if type.nil?
assert_initialized
target_type = type
single_type = @single_type
if @init_args.empty?
@new_function ||= Puppet::Functions.create_function(:new_Init, Puppet::Functions::InternalFunction) do
@target_type = target_type
@single_type = single_type
dispatch :from_array do
scope_param
param 'Array', :value
end
dispatch :create do
scope_param
param 'Any', :value
end
def self.create(scope, value, func)
func.call(scope, @target_type, value)
end
def self.from_array(scope, value, func)
# If there is a single argument that matches the array, then that gets priority over
# expanding the array into all arguments
if @single_type.instance?(value) || (@other_type && !@other_type.instance?(value) && @has_optional_single && @other_type.instance?([value]))
func.call(scope, @target_type, value)
else
func.call(scope, @target_type, *value)
end
end
def from_array(scope, value)
self.class.from_array(scope, value, loader.load(:function, 'new'))
end
def create(scope, value)
self.class.create(scope, value, loader.load(:function, 'new'))
end
end
else
init_args = @init_args
@new_function ||= Puppet::Functions.create_function(:new_Init, Puppet::Functions::InternalFunction) do
@target_type = target_type
@init_args = init_args
dispatch :create do
scope_param
param 'Any', :value
end
def self.create(scope, value, func)
func.call(scope, @target_type, value, *@init_args)
end
def create(scope, value)
self.class.create(scope, value, loader.load(:function, 'new'))
end
end
end
end
DEFAULT = PInitType.new(nil, EMPTY_ARRAY)
EXACTLY_ONE = [1, 1].freeze
def assert_initialized
return self if @initialized
@initialized = true
@self_recursion = true
begin
# Filter out types that will provide a new_function but are unsuitable to be contained in Init
#
# Calling Init#new would cause endless recursion
# The Optional is the same as Variant[T,Undef].
# The NotUndef is not meaningful to create instances of
if @type.instance_of?(PInitType) || @type.instance_of?(POptionalType) || @type.instance_of?(PNotUndefType)
raise ArgumentError
end
new_func = @type.new_function
rescue ArgumentError
raise ArgumentError, _("Creation of new instance of type '%{type_name}' is not supported") % { type_name: @type.to_s }
end
param_tuples = new_func.dispatcher.signatures.map { |closure| closure.type.param_types }
# An instance of the contained type is always a match to this type.
single_types = [@type]
if @init_args.empty?
# A value that is assignable to the type of a single parameter is also a match
single_tuples, other_tuples = param_tuples.partition { |tuple| EXACTLY_ONE == tuple.size_range }
single_types.concat(single_tuples.map { |tuple| tuple.types[0] })
else
tc = TypeCalculator.singleton
init_arg_types = @init_args.map { |arg| tc.infer_set(arg) }
arg_count = 1 + init_arg_types.size
# disqualify all parameter tuples that doesn't allow one value (type unknown at ths stage) + init args.
param_tuples = param_tuples.select do |tuple|
min, max = tuple.size_range
if arg_count >= min && arg_count <= max
# Aside from the first parameter, does the other parameters match?
tuple.assignable?(PTupleType.new(tuple.types[0..0].concat(init_arg_types)))
else
false
end
end
if param_tuples.empty?
raise ArgumentError, _("The type '%{type}' does not represent a valid set of parameters for %{subject}.new()") %
{ type: to_s, subject: @type.generalize.name }
end
single_types.concat(param_tuples.map { |tuple| tuple.types[0] })
other_tuples = EMPTY_ARRAY
end
@single_type = PVariantType.maybe_create(single_types)
unless other_tuples.empty?
@other_type = PVariantType.maybe_create(other_tuples)
@has_optional_single = other_tuples.any? { |tuple| tuple.size_range.min == 1 }
end
guard = RecursionGuard.new
accept(NoopTypeAcceptor::INSTANCE, guard)
@self_recursion = guard.recursive_this?(self)
end
def accept(visitor, guard)
guarded_recursion(guard, nil) do |g|
super(visitor, g)
@single_type.accept(visitor, guard) if @single_type
@other_type.accept(visitor, guard) if @other_type
end
end
protected
def _assignable?(o, guard)
guarded_recursion(guard, false) do |g|
assert_initialized
if o.is_a?(PInitType)
@type.nil? || @type.assignable?(o.type, g)
elsif @type.nil?
TypeFactory.rich_data.assignable?(o, g)
else
@type.assignable?(o, g) ||
@single_type && @single_type.assignable?(o, g) ||
@other_type && (@other_type.assignable?(o, g) || @has_optional_single && @other_type.assignable?(PTupleType.new([o])))
end
end
end
private
def guarded_recursion(guard, dflt)
if @self_recursion
guard ||= RecursionGuard.new
guard.with_this(self) { |state| (state & RecursionGuard::SELF_RECURSION_IN_THIS) == 0 ? yield(guard) : dflt }
else
yield(guard)
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/type_asserter.rb | lib/puppet/pops/types/type_asserter.rb | # frozen_string_literal: true
# Utility module for type assertion
#
module Puppet::Pops::Types
module TypeAsserter
# Asserts that a type_to_check is assignable to required_type and raises
# a {Puppet::ParseError} if that's not the case
#
# @param subject [String,Array] String to be prepended to the exception message or Array where the first element is
# a format string and the rest are arguments to that format string
# @param expected_type [PAnyType] Expected type
# @param type_to_check [PAnyType] Type to check against the required type
# @return The type_to_check argument
#
# @api public
def self.assert_assignable(subject, expected_type, type_to_check, &block)
report_type_mismatch(subject, expected_type, type_to_check, 'is incorrect', &block) unless expected_type.assignable?(type_to_check)
type_to_check
end
# Asserts that a value is an instance of a given type and raises
# a {Puppet::ParseError} if that's not the case
#
# @param subject [String,Array] String to be prepended to the exception message or Array where the first element is
# a format string and the rest are arguments to that format string
# @param expected_type [PAnyType] Expected type for the value
# @param value [Object] Value to check
# @param nil_ok [Boolean] Can be true to allow nil value. Optional and defaults to false
# @return The value argument
#
# @api public
def self.assert_instance_of(subject, expected_type, value, nil_ok = false, &block)
unless value.nil? && nil_ok
report_type_mismatch(subject, expected_type, TypeCalculator.singleton.infer_set(value), &block) unless expected_type.instance?(value)
end
value
end
def self.report_type_mismatch(subject, expected_type, actual_type, what = 'has wrong type')
subject = yield(subject) if block_given?
subject = subject[0] % subject[1..] if subject.is_a?(Array)
raise TypeAssertionError.new(
TypeMismatchDescriber.singleton.describe_mismatch("#{subject} #{what},", expected_type, actual_type), expected_type, actual_type
)
end
private_class_method :report_type_mismatch
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/type_conversion_error.rb | lib/puppet/pops/types/type_conversion_error.rb | # frozen_string_literal: true
module Puppet::Pops::Types
# Raised when a conversion of a value to another type failed.
#
class TypeConversionError < Puppet::Error; end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/puppet_object.rb | lib/puppet/pops/types/puppet_object.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
# Marker module for implementations that are mapped to Object types
# @api public
module PuppetObject
# Returns the Puppet Type for this instance. The implementing class must
# add the {#_pcore_type} as a class method.
#
# @return [PObjectType] the type
def _pcore_type
t = self.class._pcore_type
if t.parameterized?
unless instance_variable_defined?(:@_cached_ptype)
# Create a parameterized type based on the values of this instance that
# contains a parameter value for each type parameter that matches an
# attribute by name and type of value
@_cached_ptype = PObjectTypeExtension.create_from_instance(t, self)
end
t = @_cached_ptype
end
t
end
def _pcore_all_contents(path, &block)
end
def _pcore_contents
end
def _pcore_init_hash
{}
end
def to_s
TypeFormatter.string(self)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/p_binary_type.rb | lib/puppet/pops/types/p_binary_type.rb | # frozen_string_literal: true
require 'base64'
module Puppet::Pops
module Types
# A Puppet Language Type that represents binary data content (a sequence of 8-bit bytes).
# Instances of this data type can be created from `String` and `Array[Integer[0,255]]`
# values. Also see the `binary_file` function for reading binary content from a file.
#
# A `Binary` can be converted to `String` and `Array` form - see function `new` for
# the respective target data type for more information.
#
# Instances of this data type serialize as base 64 encoded strings when the serialization
# format is textual, and as binary content when a serialization format supports this.
#
# @api public
class PBinaryType < PAnyType
# Represents a binary buffer
# @api public
class Binary
attr_reader :binary_buffer
# Constructs an instance of Binary from a base64 urlsafe encoded string (RFC 2045).
# @param [String] A string with RFC 2045 compliant encoded binary
#
def self.from_base64(str)
new(Base64.decode64(str))
end
# Constructs an instance of Binary from a base64 encoded string (RFC4648 with "URL and Filename
# Safe Alphabet" (That is with '-' instead of '+', and '_' instead of '/').
#
def self.from_base64_urlsafe(str)
new(Base64.urlsafe_decode64(str))
end
# Constructs an instance of Binary from a base64 strict encoded string (RFC 4648)
# Where correct padding must be used and line breaks causes an error to be raised.
#
# @param [String] A string with RFC 4648 compliant encoded binary
#
def self.from_base64_strict(str)
new(Base64.strict_decode64(str))
end
# Creates a new Binary from a String containing binary data. If the string's encoding
# is not already ASCII-8BIT, a copy of the string is force encoded as ASCII-8BIT (that is Ruby's "binary" format).
# This means that this binary will have the exact same content, but the string will considered
# to hold a sequence of bytes in the range 0 to 255.
#
# The given string will be frozen as a side effect if it is in ASCII-8BIT encoding. If this is not
# wanted, a copy should be given to this method.
#
# @param [String] A string with binary data
# @api public
#
def self.from_binary_string(bin)
new(bin)
end
# Creates a new Binary from a String containing text/binary in its given encoding. If the string's encoding
# is not already UTF-8, the string is first transcoded to UTF-8.
# This means that this binary will have the UTF-8 byte representation of the original string.
# For this to be valid, the encoding used in the given string must be valid.
# The validity of the given string is therefore asserted.
#
# The given string will be frozen as a side effect if it is in ASCII-8BIT encoding. If this is not
# wanted, a copy should be given to this method.
#
# @param [String] A string with valid content in its given encoding
# @return [Puppet::Pops::Types::PBinaryType::Binary] with the UTF-8 representation of the UTF-8 transcoded string
# @api public
#
def self.from_string(encoded_string)
enc = encoded_string.encoding.name
unless encoded_string.valid_encoding?
raise ArgumentError, _("The given string in encoding '%{enc}' is invalid. Cannot create a Binary UTF-8 representation") % { enc: enc }
end
# Convert to UTF-8 (if not already UTF-8), and then to binary
encoded_string = (enc == "UTF-8") ? encoded_string.dup : encoded_string.encode('UTF-8')
encoded_string.force_encoding("ASCII-8BIT")
new(encoded_string)
end
# Creates a new Binary from a String containing raw binary data of unknown encoding. If the string's encoding
# is not already ASCII-8BIT, a copy of the string is forced to ASCII-8BIT (that is Ruby's "binary" format).
# This means that this binary will have the exact same content, but the string will considered
# to hold a sequence of bytes in the range 0 to 255.
#
# @param [String] A string with binary data
# @api private
#
def initialize(bin)
@binary_buffer = (bin.encoding.name == "ASCII-8BIT" ? bin : bin.b).freeze
end
# Presents the binary content as a string base64 encoded string (without line breaks).
#
def to_s
Base64.strict_encode64(@binary_buffer)
end
# Returns the binary content as a "relaxed" base64 (standard) encoding where
# the string is broken up with new lines.
def relaxed_to_s
Base64.encode64(@binary_buffer)
end
# Returns the binary content as a url safe base64 string (where + and / are replaced by - and _)
#
def urlsafe_to_s
Base64.urlsafe_encode64(@binary_buffer)
end
def hash
@binary_buffer.hash
end
def eql?(o)
self.class == o.class && @binary_buffer == o.binary_buffer
end
def ==(o)
eql?(o)
end
def length
@binary_buffer.length
end
end
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'AnyType')
end
# Only instances of Binary are instances of the PBinaryType
#
def instance?(o, guard = nil)
o.is_a?(Binary)
end
def eql?(o)
self.class == o.class
end
# Binary uses the strict base64 format as its string representation
# @return [TrueClass] true
def roundtrip_with_string?
true
end
# @api private
def self.new_function(type)
@new_function ||= Puppet::Functions.create_loaded_function(:new_Binary, type.loader) do
local_types do
type 'ByteInteger = Integer[0,255]'
type 'Base64Format = Enum["%b", "%u", "%B", "%s", "%r"]'
type 'StringHash = Struct[{value => String, "format" => Optional[Base64Format]}]'
type 'ArrayHash = Struct[{value => Array[ByteInteger]}]'
type 'BinaryArgsHash = Variant[StringHash, ArrayHash]'
end
# Creates a binary from a base64 encoded string in one of the formats %b, %u, %B, %s, or %r
dispatch :from_string do
param 'String', :str
optional_param 'Base64Format', :format
end
dispatch :from_array do
param 'Array[ByteInteger]', :byte_array
end
# Same as from_string, or from_array, but value and (for string) optional format are given in the form
# of a hash.
#
dispatch :from_hash do
param 'BinaryArgsHash', :hash_args
end
def from_string(str, format = nil)
format ||= '%B'
case format
when "%b"
# padding must be added for older rubies to avoid truncation
padding = '=' * (str.length % 3)
Binary.new(Base64.decode64(str + padding))
when "%u"
Binary.new(Base64.urlsafe_decode64(str))
when "%B"
Binary.new(Base64.strict_decode64(str))
when "%s"
Binary.from_string(str)
when "%r"
Binary.from_binary_string(str)
else
raise ArgumentError, "Unsupported Base64 format '#{format}'"
end
end
def from_array(array)
# The array is already known to have bytes in the range 0-255, or it is in error
# Without this pack C would produce weird results
Binary.from_binary_string(array.pack("C*"))
end
def from_hash(hash)
case hash['value']
when Array
from_array(hash['value'])
when String
from_string(hash['value'], hash['format'])
end
end
end
end
DEFAULT = PBinaryType.new
protected
def _assignable?(o, guard)
o.instance_of?(self.class)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/class_loader.rb | lib/puppet/pops/types/class_loader.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
# The ClassLoader provides a Class instance given a class name or a meta-type.
# If the class is not already loaded, it is loaded using the Puppet Autoloader.
# This means it can load a class from a gem, or from puppet modules.
#
class ClassLoader
@autoloader = Puppet::Util::Autoload.new("ClassLoader", "")
# Returns a Class given a fully qualified class name.
# Lookup of class is never relative to the calling namespace.
# @param name [String, Array<String>, Array<Symbol>, PAnyType] A fully qualified
# class name String (e.g. '::Foo::Bar', 'Foo::Bar'), a PAnyType, or a fully qualified name in Array form where each part
# is either a String or a Symbol, e.g. `%w{Puppetx Puppetlabs SomeExtension}`.
# @return [Class, nil] the looked up class or nil if no such class is loaded
# @raise ArgumentError If the given argument has the wrong type
# @api public
#
def self.provide(name)
case name
when String
provide_from_string(name)
when Array
provide_from_name_path(name.join('::'), name)
when PAnyType, PTypeType
provide_from_type(name)
else
raise ArgumentError, "Cannot provide a class from a '#{name.class.name}'"
end
end
def self.provide_from_type(type)
case type
when PRuntimeType
raise ArgumentError, "Only Runtime type 'ruby' is supported, got #{type.runtime}" unless type.runtime == :ruby
provide_from_string(type.runtime_type_name)
when PBooleanType
# There is no other thing to load except this Enum meta type
RGen::MetamodelBuilder::MMBase::Boolean
when PTypeType
# TODO: PTypeType should have a type argument (a PAnyType) so the Class' class could be returned
# (but this only matters in special circumstances when meta programming has been used).
Class
when POptionalType
# cannot make a distinction between optional and its type
provide_from_type(type.optional_type)
# Although not expected to be the first choice for getting a concrete class for these
# types, these are of value if the calling logic just has a reference to type.
# rubocop:disable Layout/SpaceBeforeSemicolon
when PArrayType ; Array
when PTupleType ; Array
when PHashType ; Hash
when PStructType ; Hash
when PRegexpType ; Regexp
when PIntegerType ; Integer
when PStringType ; String
when PPatternType ; String
when PEnumType ; String
when PFloatType ; Float
when PUndefType ; NilClass
when PCallableType ; Proc
# rubocop:enable Layout/SpaceBeforeSemicolon
else
nil
end
end
private_class_method :provide_from_type
def self.provide_from_string(name)
name_path = name.split(TypeFormatter::NAME_SEGMENT_SEPARATOR)
# always from the root, so remove an empty first segment
name_path.shift if name_path[0].empty?
provide_from_name_path(name, name_path)
end
def self.provide_from_name_path(name, name_path)
# If class is already loaded, try this first
result = find_class(name_path)
unless result.is_a?(Module)
# Attempt to load it using the auto loader
loaded_path = nil
if paths_for_name(name_path).find { |path| loaded_path = path; @autoloader.load(path, Puppet.lookup(:current_environment)) }
result = find_class(name_path)
unless result.is_a?(Module)
raise RuntimeError, "Loading of #{name} using relative path: '#{loaded_path}' did not create expected class"
end
end
end
return nil unless result.is_a?(Module)
result
end
private_class_method :provide_from_string
def self.find_class(name_path)
name_path.reduce(Object) do |ns, name|
ns.const_get(name, false) # don't search ancestors
rescue NameError
return nil
end
end
private_class_method :find_class
def self.paths_for_name(fq_named_parts)
# search two entries, one where all parts are decamelized, and one with names just downcased
# TODO:this is not perfect - it will not produce the correct mix if a mix of styles are used
# The alternative is to test many additional paths.
#
[fq_named_parts.map { |part| de_camel(part) }.join('/'), fq_named_parts.join('/').downcase]
end
private_class_method :paths_for_name
def self.de_camel(fq_name)
fq_name.to_s.gsub(/::/, '/')
.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
.gsub(/([a-z\d])([A-Z])/, '\1_\2')
.tr("-", "_")
.downcase
end
private_class_method :de_camel
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/tree_iterators.rb | lib/puppet/pops/types/tree_iterators.rb | # frozen_string_literal: true
module Puppet::Pops::Types
module Iterable
class TreeIterator
include Iterable
DEFAULT_CONTAINERS = TypeFactory.variant(
PArrayType::DEFAULT,
PHashType::DEFAULT,
PObjectType::DEFAULT
)
# Creates a TreeIterator that by default treats all Array, Hash and Object instances as
# containers - the 'containers' option can be set to a type that denotes which types of values
# should be treated as containers - a `Variant[Array, Hash]` would for instance not treat
# Object values as containers, whereas just `Object` would only treat objects as containers.
#
# Unrecognized options are silently ignored
#
# @param [Hash] options the options
# @option options [PTypeType] :container_type ('Variant[Hash, Array, Object]') The type(s) that should be treated as containers. The
# given type(s) must be assignable to the default container_type.
# @option options [Boolean] :include_root ('true') If the root container itself should be included in the iteration (requires
# `include_containers` to also be `true` to take effect).
# @option options [Boolean] :include_containers ('true') If containers should be included in the iteration
# @option options [Boolean] :include_values ('true') If non containers (values) should be included in the iteration
# @option options [Boolean] :include_refs ('false') If (non containment) referenced values in Objects should be included
#
def initialize(enum, options = EMPTY_HASH)
@root = enum
@element_t = nil
@value_stack = [enum]
@indexer_stack = []
@current_path = []
@recursed = false
@containers_t = options['container_type'] || DEFAULT_CONTAINERS
unless DEFAULT_CONTAINERS.assignable?(@containers_t)
raise ArgumentError, _("Only Array, Hash, and Object types can be used as container types. Got %{type}") % { type: @containers_t }
end
@with_root = extract_option(options, 'include_root', true)
@with_containers = extract_option(options, 'include_containers', true)
@with_values = extract_option(options, 'include_values', true)
@with_root = @with_containers && extract_option(options, 'include_root', true)
unless @with_containers || @with_values
raise ArgumentError, _("Options 'include_containers' and 'include_values' cannot both be false")
end
@include_refs = !!options['include_refs']
end
# Yields each `path, value` if the block arity is 2, and only `value` if arity is 1
#
def each(&block)
loop do
if block.arity == 1
yield(self.next)
else
yield(*self.next)
end
end
end
def size
raise "Not yet implemented - computes size lazily"
end
def unbounded?
false
end
def to_a
result = []
loop do
result << self.next
end
result
end
def to_array
to_a
end
def reverse_each(&block)
r = Iterator.new(PAnyType::DEFAULT, to_array.reverse_each)
block_given? ? r.each(&block) : r
end
def step(step, &block)
r = StepIterator.new(PAnyType::DEFAULT, self, step)
block_given? ? r.each(&block) : r
end
def indexer_on(val)
return nil unless @containers_t.instance?(val)
if val.is_a?(Array)
val.size.times
elsif val.is_a?(Hash)
val.each_key
elsif @include_refs
val._pcore_type.attributes.each_key
else
val._pcore_type.attributes.reject { |_k, v| v.kind == PObjectType::ATTRIBUTE_KIND_REFERENCE }.each_key
end
end
private :indexer_on
def has_next?(iterator)
iterator.peek
true
rescue StopIteration
false
end
private :has_next?
def extract_option(options, key, default)
v = options[key]
v.nil? ? default : !!v
end
private :extract_option
end
class DepthFirstTreeIterator < TreeIterator
# Creates a DepthFirstTreeIterator that by default treats all Array, Hash and Object instances as
# containers - the 'containers' option can be set to a type that denotes which types of values
# should be treated as containers - a `Variant[Array, Hash]` would for instance not treat
# Object values as containers, whereas just `Object` would only treat objects as containers.
#
# @param [Hash] options the options
# @option options [PTypeType] :containers ('Variant[Hash, Array, Object]') The type(s) that should be treated as containers
# @option options [Boolean] :with_root ('true') If the root container itself should be included in the iteration
#
def initialize(enum, options = EMPTY_HASH)
super
end
def next
loop do
break if @value_stack.empty?
# first call
if @indexer_stack.empty?
@indexer_stack << indexer_on(@root)
@recursed = true
return [[], @root] if @with_root
end
begin
if @recursed
@current_path << nil
@recursed = false
end
idx = @indexer_stack[-1].next
@current_path[-1] = idx
v = @value_stack[-1]
value = v.is_a?(PuppetObject) ? v.send(idx) : v[idx]
indexer = indexer_on(value)
if indexer
# recurse
@recursed = true
@value_stack << value
@indexer_stack << indexer
redo unless @with_containers
else
redo unless @with_values
end
return [@current_path.dup, value]
rescue StopIteration
# end of current value's range of content
# pop all until out of next values
at_the_very_end = false
loop do
pop_level
at_the_very_end = @indexer_stack.empty?
break if at_the_very_end || has_next?(@indexer_stack[-1])
end
end
end
raise StopIteration
end
def pop_level
@value_stack.pop
@indexer_stack.pop
@current_path.pop
end
private :pop_level
end
class BreadthFirstTreeIterator < TreeIterator
def initialize(enum, options = EMPTY_HASH)
@path_stack = []
super
end
def next
loop do
break if @value_stack.empty?
# first call
if @indexer_stack.empty?
@indexer_stack << indexer_on(@root)
@recursed = true
return [[], @root] if @with_root
end
begin
if @recursed
@current_path << nil
@recursed = false
end
idx = @indexer_stack[0].next
@current_path[-1] = idx
v = @value_stack[0]
value = v.is_a?(PuppetObject) ? v.send(idx) : v[idx]
indexer = indexer_on(value)
if indexer
@value_stack << value
@indexer_stack << indexer
@path_stack << @current_path.dup
next unless @with_containers
end
return [@current_path.dup, value]
rescue StopIteration
# end of current value's range of content
# shift all until out of next values
at_the_very_end = false
loop do
shift_level
at_the_very_end = @indexer_stack.empty?
break if at_the_very_end || has_next?(@indexer_stack[0])
end
end
end
raise StopIteration
end
def shift_level
@value_stack.shift
@indexer_stack.shift
@current_path = @path_stack.shift
@recursed = true
end
private :shift_level
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/type_with_members.rb | lib/puppet/pops/types/type_with_members.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
# Interface implemented by a type that has InvocableMembers
module TypeWithMembers
# @return [InvocableMember,nil] An invocable member if it exists, or `nil`
def [](member_name)
raise NotImplementedError, "'#{self.class.name}' should implement #[]"
end
end
# Interface implemented by attribute and function members
module InvocableMember
# Performs type checking of arguments and invokes the method that corresponds to this
# method. The result of the invocation is returned
#
# @param receiver [Object] The receiver of the call
# @param scope [Puppet::Parser::Scope] The caller scope
# @param args [Array] Array of arguments.
# @return [Object] The result returned by the member function or attribute
#
# @api private
def invoke(receiver, scope, args, &block)
raise NotImplementedError, "'#{self.class.name}' should implement #invoke"
end
end
# Plays the same role as an PAttribute in the PObjectType. Provides
# access to known attr_readers and plain reader methods.
class AttrReader
include InvocableMember
def initialize(message)
@message = message.to_sym
end
def invoke(receiver, scope, args, &block)
receiver.send(@message)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/types.rb | lib/puppet/pops/types/types.rb | # frozen_string_literal: true
require_relative 'iterable'
require_relative 'recursion_guard'
require_relative 'type_acceptor'
require_relative 'type_asserter'
require_relative 'type_assertion_error'
require_relative 'type_conversion_error'
require_relative 'type_formatter'
require_relative 'type_calculator'
require_relative 'type_factory'
require_relative 'type_parser'
require_relative 'class_loader'
require_relative 'type_mismatch_describer'
require_relative 'puppet_object'
module Puppet::Pops
module Types
# The EMPTY_xxx declarations is for backward compatibility. They should not be explicitly referenced
# @api private
# @deprecated
EMPTY_HASH = Puppet::Pops::EMPTY_HASH
# @api private
# @deprecated
EMPTY_ARRAY = Puppet::Pops::EMPTY_ARRAY
# @api private
# @deprecated
EMPTY_STRING = Puppet::Pops::EMPTY_STRING
# The Types model is a model of Puppet Language types.
#
# The {TypeCalculator} should be used to answer questions about types. The {TypeFactory} or {TypeParser} should be used
# to create an instance of a type whenever one is needed.
#
# The implementation of the Types model contains methods that are required for the type objects to behave as
# expected when comparing them and using them as keys in hashes. (No other logic is, or should be included directly in
# the model's classes).
#
# @api public
#
class TypedModelObject < Object
include PuppetObject
include Visitable
include Adaptable
def self._pcore_type
@type
end
def self.create_ptype(loader, ir, parent_name, attributes_hash = EMPTY_HASH)
@type = Pcore.create_object_type(loader, ir, self, "Pcore::#{simple_name}Type", "Pcore::#{parent_name}", attributes_hash)
end
def self.register_ptypes(loader, ir)
types = [
Annotation.register_ptype(loader, ir),
RubyMethod.register_ptype(loader, ir)
]
Types.constants.each do |c|
next if c == :PType || c == :PHostClassType
cls = Types.const_get(c)
next unless cls.is_a?(Class) && cls < self
type = cls.register_ptype(loader, ir)
types << type unless type.nil?
end
types.each { |type| type.resolve(loader) }
end
end
# Base type for all types
# @api public
#
class PAnyType < TypedModelObject
def self.register_ptype(loader, ir)
@type = Pcore.create_object_type(loader, ir, self, 'Pcore::AnyType', 'Any', EMPTY_HASH)
end
def self.create(*args)
# NOTE! Important to use self::DEFAULT and not just DEFAULT since the latter yields PAnyType::DEFAULT
args.empty? ? self::DEFAULT : new(*args)
end
# Accept a visitor that will be sent the message `visit`, once with `self` as the
# argument. The visitor will then visit all types that this type contains.
#
def accept(visitor, guard)
visitor.visit(self, guard)
end
# Checks if _o_ is a type that is assignable to this type.
# If _o_ is a `Class` then it is first converted to a type.
# If _o_ is a Variant, then it is considered assignable when all its types are assignable
#
# The check for assignable must be guarded against self recursion since `self`, the given type _o_,
# or both, might be a `TypeAlias`. The initial caller of this method will typically never care
# about this and hence pass only the first argument, but as soon as a check of a contained type
# encounters a `TypeAlias`, then a `RecursionGuard` instance is created and passed on in all
# subsequent calls. The recursion is allowed to continue until self recursion has been detected in
# both `self` and in the given type. At that point the given type is considered to be assignable
# to `self` since all checks up to that point were positive.
#
# @param o [Class,PAnyType] the class or type to test
# @param guard [RecursionGuard] guard against recursion. Only used by internal calls
# @return [Boolean] `true` when _o_ is assignable to this type
# @api public
def assignable?(o, guard = nil)
case o
when Class
# Safe to call _assignable directly since a Class never is a Unit or Variant
_assignable?(TypeCalculator.singleton.type(o), guard)
when PUnitType
true
when PTypeAliasType
# An alias may contain self recursive constructs.
if o.self_recursion?
guard ||= RecursionGuard.new
if guard.add_that(o) == RecursionGuard::SELF_RECURSION_IN_BOTH
# Recursion detected both in self and other. This means that other is assignable
# to self. This point would not have been reached otherwise
true
else
assignable?(o.resolved_type, guard)
end
else
assignable?(o.resolved_type, guard)
end
when PVariantType
# Assignable if all contained types are assignable, or if this is exactly Any
return true if instance_of?(PAnyType)
# An empty variant may be assignable to NotUndef[T] if T is assignable to empty variant
return _assignable?(o, guard) if is_a?(PNotUndefType) && o.types.empty?
!o.types.empty? && o.types.all? { |vt| assignable?(vt, guard) }
when POptionalType
# Assignable if undef and contained type is assignable
assignable?(PUndefType::DEFAULT) && (o.type.nil? || assignable?(o.type))
when PNotUndefType
if !(o.type.nil? || o.type.assignable?(PUndefType::DEFAULT))
assignable?(o.type, guard)
else
_assignable?(o, guard)
end
else
_assignable?(o, guard)
end
end
# Returns `true` if this instance is a callable that accepts the given _args_type_ type
#
# @param args_type [PAnyType] the arguments to test
# @param guard [RecursionGuard] guard against recursion. Only used by internal calls
# @return [Boolean] `true` if this instance is a callable that accepts the given _args_
def callable?(args_type, guard = nil)
args_type.is_a?(PAnyType) && kind_of_callable? && args_type.callable_args?(self, guard)
end
# Returns `true` if this instance is a callable that accepts the given _args_
#
# @param args [Array] the arguments to test
# @param block [Proc] block, or nil if not called with a block
# @return [Boolean] `true` if this instance is a callable that accepts the given _args_
def callable_with?(args, block = nil)
false
end
# Returns `true` if this instance is considered valid as arguments to the given `callable`
# @param callable [PAnyType] the callable
# @param guard [RecursionGuard] guard against recursion. Only used by internal calls
# @return [Boolean] `true` if this instance is considered valid as arguments to the given `callable`
# @api private
def callable_args?(callable, guard)
false
end
# Called from the `PTypeAliasType` when it detects self recursion. The default is to do nothing
# but some self recursive constructs are illegal such as when a `PObjectType` somehow inherits itself
# @param originator [PTypeAliasType] the starting point for the check
# @raise Puppet::Error if an illegal self recursion is detected
# @api private
def check_self_recursion(originator)
end
# Generalizes value specific types. Types that are not value specific will return `self` otherwise
# the generalized type is returned.
#
# @return [PAnyType] The generalized type
# @api public
def generalize
# Applicable to all types that have no variables
self
end
# Returns the loader that loaded this type.
# @return [Loaders::Loader] the loader
def loader
Loaders.static_loader
end
# Normalizes the type. This does not change the characteristics of the type but it will remove duplicates
# and constructs like NotUndef[T] where T is not assignable from Undef and change Variant[*T] where all
# T are enums into an Enum.
#
# @param guard [RecursionGuard] guard against recursion. Only used by internal calls
# @return [PAnyType] The iterable type that this type is assignable to or `nil`
# @api public
def normalize(guard = nil)
self
end
# Called from the TypeParser once it has found a type using the Loader to enable that this type can
# resolve internal type expressions using a loader. Presently, this method is a no-op for all types
# except the {{PTypeAliasType}}.
#
# @param loader [Loader::Loader] loader to use
# @return [PTypeAliasType] the receiver of the call, i.e. `self`
# @api private
def resolve(loader)
self
end
# Responds `true` for all callables, variants of callables and unless _optional_ is
# false, all optional callables.
# @param optional [Boolean]
# @param guard [RecursionGuard] guard against recursion. Only used by internal calls
# @return [Boolean] `true`if this type is considered callable
# @api private
def kind_of_callable?(optional = true, guard = nil)
false
end
# Returns `true` if an instance of this type is iterable, `false` otherwise
# The method #iterable_type must produce a `PIterableType` instance when this
# method returns `true`
#
# @param guard [RecursionGuard] guard against recursion. Only used by internal calls
# @return [Boolean] flag to indicate if instances of this type is iterable.
def iterable?(guard = nil)
false
end
# Returns the `PIterableType` that this type should be assignable to, or `nil` if no such type exists.
# A type that returns a `PIterableType` must respond `true` to `#iterable?`.
#
# @example
# Any Collection[T] is assignable to an Iterable[T]
# A String is assignable to an Iterable[String] iterating over the strings characters
# An Integer is assignable to an Iterable[Integer] iterating over the 'times' enumerator
# A Type[T] is assignable to an Iterable[Type[T]] if T is an Integer or Enum
#
# @param guard [RecursionGuard] guard against recursion. Only used by internal calls
# @return [PIterableType,nil] The iterable type that this type is assignable to or `nil`
# @api private
def iterable_type(guard = nil)
nil
end
def hash
self.class.hash
end
# Returns true if the given argument _o_ is an instance of this type
# @param guard [RecursionGuard] guard against recursion. Only used by internal calls
# @return [Boolean]
# @api public
def instance?(o, guard = nil)
true
end
# An object is considered to really be an instance of a type when something other than a
# TypeAlias or a Variant responds true to a call to {#instance?}.
#
# @return [Integer] -1 = is not instance, 0 = recursion detected, 1 = is instance
# @api private
def really_instance?(o, guard = nil)
instance?(o, guard) ? 1 : -1
end
def eql?(o)
self.class == o.class
end
def ==(o)
eql?(o)
end
def simple_name
self.class.simple_name
end
# Strips the class name from all module prefixes, the leading 'P' and the ending 'Type'. I.e.
# an instance of PVariantType will return 'Variant'
# @return [String] the simple name of this type
def self.simple_name
@simple_name ||= (
n = name
n[n.rindex(DOUBLE_COLON) + 3..n.size - 5].freeze
)
end
def to_alias_expanded_s
TypeFormatter.new.alias_expanded_string(self)
end
def to_s
TypeFormatter.string(self)
end
# Returns the name of the type, without parameters
# @return [String] the name of the type
# @api public
def name
simple_name
end
def create(*args)
Loaders.find_loader(nil).load(:function, 'new').call({}, self, *args)
end
# Create an instance of this type.
# The default implementation will just dispatch the call to the class method with the
# same name and pass `self` as the first argument.
#
# @return [Function] the created function
# @raises ArgumentError
#
def new_function
self.class.new_function(self)
end
# This default implementation of of a new_function raises an Argument Error.
# Types for which creating a new instance is supported, should create and return
# a Puppet Function class by using Puppet:Loaders.create_loaded_function(:new, loader)
# and return that result.
#
# @param type [PAnyType] the type to create a new function for
# @return [Function] the created function
# @raises ArgumentError
#
def self.new_function(type)
raise ArgumentError, "Creation of new instance of type '#{type}' is not supported"
end
# Answers the question if instances of this type can represent themselves as a string that
# can then be passed to the create method
#
# @return [Boolean] whether or not the instance has a canonical string representation
def roundtrip_with_string?
false
end
# The default instance of this type. Each type in the type system has this constant
# declared.
#
DEFAULT = PAnyType.new
protected
# @api private
def _assignable?(o, guard)
o.is_a?(PAnyType)
end
# Produces the tuple entry at the given index given a tuple type, its from/to constraints on the last
# type, and an index.
# Produces nil if the index is out of bounds
# from must be less than to, and from may not be less than 0
#
# @api private
#
def tuple_entry_at(tuple_t, to, index)
regular = (tuple_t.types.size - 1)
if index < regular
tuple_t.types[index]
elsif index < regular + to
# in the varargs part
tuple_t.types[-1]
else
nil
end
end
# Applies a transformation by sending the given _method_ and _method_args_ to each of the types of the given array
# and collecting the results in a new array. If all transformation calls returned the type instance itself (i.e. no
# transformation took place), then this method will return `self`. If a transformation did occur, then this method
# will either return the transformed array or in case a block was given, the result of calling a given block with
# the transformed array.
#
# @param types [Array<PAnyType>] the array of types to transform
# @param method [Symbol] The method to call on each type
# @param method_args [Object] The arguments to pass to the method, if any
# @return [Object] self, the transformed array, or the result of calling a given block with the transformed array
# @yieldparam altered_types [Array<PAnyType>] the altered type array
# @api private
def alter_type_array(types, method, *method_args)
modified = false
modified_types = types.map do |t|
t_mod = t.send(method, *method_args)
modified ||= !t.equal?(t_mod)
t_mod
end
if modified
block_given? ? yield(modified_types) : modified_types
else
self
end
end
end
# @abstract Encapsulates common behavior for a type that contains one type
# @api public
class PTypeWithContainedType < PAnyType
def self.register_ptype(loader, ir)
# Abstract type. It doesn't register anything
end
attr_reader :type
def initialize(type)
@type = type
end
def accept(visitor, guard)
super
@type.accept(visitor, guard) unless @type.nil?
end
def generalize
if @type.nil?
self.class::DEFAULT
else
ge_type = @type.generalize
@type.equal?(ge_type) ? self : self.class.new(ge_type)
end
end
def normalize(guard = nil)
if @type.nil?
self.class::DEFAULT
else
ne_type = @type.normalize(guard)
@type.equal?(ne_type) ? self : self.class.new(ne_type)
end
end
def hash
self.class.hash ^ @type.hash
end
def eql?(o)
self.class == o.class && @type == o.type
end
def resolve(loader)
rtype = @type
rtype = rtype.resolve(loader) unless rtype.nil?
rtype.equal?(@type) ? self : self.class.new(rtype)
end
end
# The type of types.
# @api public
#
class PTypeType < PTypeWithContainedType
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'AnyType',
'type' => {
KEY_TYPE => POptionalType.new(PTypeType::DEFAULT),
KEY_VALUE => nil
})
end
# Returns a new function that produces a Type instance
#
def self.new_function(type)
@new_function ||= Puppet::Functions.create_loaded_function(:new_type, type.loader) do
dispatch :from_string do
param 'String[1]', :type_string
end
def from_string(type_string)
TypeParser.singleton.parse(type_string, loader)
end
end
end
def instance?(o, guard = nil)
case o
when PAnyType
type.nil? || type.assignable?(o, guard)
when Module, Puppet::Resource, Puppet::Parser::Resource
@type.nil? ? true : assignable?(TypeCalculator.infer(o))
else
false
end
end
def iterable?(guard = nil)
case @type
when PEnumType
true
when PIntegerType
@type.finite_range?
else
false
end
end
def iterable_type(guard = nil)
# The types PIntegerType and PEnumType are Iterable
case @type
when PEnumType
# @type describes the element type perfectly since the iteration is made over the
# contained choices.
PIterableType.new(@type)
when PIntegerType
# @type describes the element type perfectly since the iteration is made over the
# specified range.
@type.finite_range? ? PIterableType.new(@type) : nil
else
nil
end
end
def eql?(o)
self.class == o.class && @type == o.type
end
DEFAULT = PTypeType.new(nil)
protected
# @api private
def _assignable?(o, guard)
return false unless o.is_a?(PTypeType)
return true if @type.nil? # wide enough to handle all types
return false if o.type.nil? # wider than t
@type.assignable?(o.type, guard)
end
end
# For backward compatibility
PType = PTypeType
class PNotUndefType < PTypeWithContainedType
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'AnyType',
'type' => {
KEY_TYPE => POptionalType.new(PTypeType::DEFAULT),
KEY_VALUE => nil
})
end
def initialize(type = nil)
super(type.instance_of?(PAnyType) ? nil : type)
end
def instance?(o, guard = nil)
!(o.nil? || o == :undef) && (@type.nil? || @type.instance?(o, guard))
end
def normalize(guard = nil)
n = super
if n.type.nil?
n
elsif n.type.is_a?(POptionalType)
PNotUndefType.new(n.type.type).normalize
# No point in having an optional in a NotUndef
elsif !n.type.assignable?(PUndefType::DEFAULT)
# THe type is NotUndef anyway, so it can be stripped of
n.type
else
n
end
end
def new_function
# If only NotUndef, then use Unit's null converter
if type.nil?
PUnitType.new_function(self)
else
type.new_function
end
end
DEFAULT = PNotUndefType.new
protected
# @api private
def _assignable?(o, guard)
o.is_a?(PAnyType) && !o.assignable?(PUndefType::DEFAULT, guard) && (@type.nil? || @type.assignable?(o, guard))
end
end
# @api public
#
class PUndefType < PAnyType
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'AnyType')
end
def instance?(o, guard = nil)
o.nil? || :undef == o
end
# @api private
def callable_args?(callable_t, guard)
# if callable_t is Optional (or indeed PUndefType), this means that 'missing callable' is accepted
callable_t.assignable?(DEFAULT, guard)
end
DEFAULT = PUndefType.new
protected
# @api private
def _assignable?(o, guard)
o.is_a?(PUndefType)
end
end
# A type private to the type system that describes "ignored type" - i.e. "I am what you are"
# @api private
#
class PUnitType < PAnyType
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'AnyType')
end
def instance?(o, guard = nil)
true
end
# A "null" implementation - that simply returns the given argument
def self.new_function(type)
@new_function ||= Puppet::Functions.create_loaded_function(:new_unit, type.loader) do
dispatch :from_args do
param 'Any', :from
end
def from_args(from)
from
end
end
end
DEFAULT = PUnitType.new
def assignable?(o, guard = nil)
true
end
protected
# @api private
def _assignable?(o, guard)
true
end
end
# @api public
#
class PDefaultType < PAnyType
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'AnyType')
end
def instance?(o, guard = nil)
# Ensure that Symbol.== is called here instead of something unknown
# that is implemented on o
:default == o
end
DEFAULT = PDefaultType.new
protected
# @api private
def _assignable?(o, guard)
o.is_a?(PDefaultType)
end
end
# Type that is a Scalar
# @api public
#
class PScalarType < PAnyType
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'AnyType')
end
def instance?(o, guard = nil)
if o.is_a?(String) || o.is_a?(Numeric) || o.is_a?(TrueClass) || o.is_a?(FalseClass) || o.is_a?(Regexp)
true
elsif o.instance_of?(Array) || o.instance_of?(Hash) || o.is_a?(PAnyType) || o.is_a?(NilClass)
false
else
assignable?(TypeCalculator.infer(o))
end
end
def roundtrip_with_string?
true
end
DEFAULT = PScalarType.new
protected
# @api private
def _assignable?(o, guard)
o.is_a?(PScalarType) ||
PStringType::DEFAULT.assignable?(o, guard) ||
PIntegerType::DEFAULT.assignable?(o, guard) ||
PFloatType::DEFAULT.assignable?(o, guard) ||
PBooleanType::DEFAULT.assignable?(o, guard) ||
PRegexpType::DEFAULT.assignable?(o, guard) ||
PSemVerType::DEFAULT.assignable?(o, guard) ||
PSemVerRangeType::DEFAULT.assignable?(o, guard) ||
PTimespanType::DEFAULT.assignable?(o, guard) ||
PTimestampType::DEFAULT.assignable?(o, guard)
end
end
# Like Scalar but limited to Json Data.
# @api public
#
class PScalarDataType < PScalarType
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'ScalarType')
end
def instance?(o, guard = nil)
o.instance_of?(String) || o.is_a?(Integer) || o.is_a?(Float) || o.is_a?(TrueClass) || o.is_a?(FalseClass)
end
DEFAULT = PScalarDataType.new
protected
# @api private
def _assignable?(o, guard)
o.is_a?(PScalarDataType) ||
PStringType::DEFAULT.assignable?(o, guard) ||
PIntegerType::DEFAULT.assignable?(o, guard) ||
PFloatType::DEFAULT.assignable?(o, guard) ||
PBooleanType::DEFAULT.assignable?(o, guard)
end
end
# A string type describing the set of strings having one of the given values
# @api public
#
class PEnumType < PScalarDataType
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'ScalarDataType',
'values' => PArrayType.new(PStringType::NON_EMPTY),
'case_insensitive' => { 'type' => PBooleanType::DEFAULT, 'value' => false })
end
attr_reader :values, :case_insensitive
def initialize(values, case_insensitive = false)
@values = values.uniq.sort.freeze
@case_insensitive = case_insensitive
end
def case_insensitive?
@case_insensitive
end
# Returns Enumerator if no block is given, otherwise, calls the given
# block with each of the strings for this enum
def each(&block)
r = Iterable.on(self)
block_given? ? r.each(&block) : r
end
def generalize
# General form of an Enum is a String
if @values.empty?
PStringType::DEFAULT
else
range = @values.map(&:size).minmax
PStringType.new(PIntegerType.new(range.min, range.max))
end
end
def iterable?(guard = nil)
true
end
def iterable_type(guard = nil)
# An instance of an Enum is a String
PStringType::ITERABLE_TYPE
end
def hash
@values.hash ^ @case_insensitive.hash
end
def eql?(o)
self.class == o.class && @values == o.values && @case_insensitive == o.case_insensitive?
end
def instance?(o, guard = nil)
if o.is_a?(String)
@case_insensitive ? @values.any? { |p| p.casecmp(o) == 0 } : @values.any? { |p| p == o }
else
false
end
end
DEFAULT = PEnumType.new(EMPTY_ARRAY)
protected
# @api private
def _assignable?(o, guard)
return true if self == o
svalues = values
if svalues.empty?
return true if o.is_a?(PStringType) || o.is_a?(PEnumType) || o.is_a?(PPatternType)
end
case o
when PStringType
# if the contained string is found in the set of enums
instance?(o.value, guard)
when PEnumType
!o.values.empty? && (case_insensitive? || !o.case_insensitive?) && o.values.all? { |s| instance?(s, guard) }
else
false
end
end
end
INTEGER_HEX = '(?:0[xX][0-9A-Fa-f]+)'
INTEGER_OCT = '(?:0[0-7]+)'
INTEGER_BIN = '(?:0[bB][01]+)'
INTEGER_DEC = '(?:0|[1-9]\d*)'
INTEGER_DEC_OR_OCT = '(?:\d+)'
SIGN_PREFIX = '[+-]?\s*'
OPTIONAL_FRACTION = '(?:\.\d+)?'
OPTIONAL_EXPONENT = '(?:[eE]-?\d+)?'
FLOAT_DEC = '(?:' + INTEGER_DEC + OPTIONAL_FRACTION + OPTIONAL_EXPONENT + ')'
INTEGER_PATTERN = '\A' + SIGN_PREFIX + '(?:' + INTEGER_DEC + '|' + INTEGER_HEX + '|' + INTEGER_OCT + '|' + INTEGER_BIN + ')\z'
INTEGER_PATTERN_LENIENT = '\A' + SIGN_PREFIX + '(?:' + INTEGER_DEC_OR_OCT + '|' + INTEGER_HEX + '|' + INTEGER_BIN + ')\z'
FLOAT_PATTERN = '\A' + SIGN_PREFIX + '(?:' + FLOAT_DEC + '|' + INTEGER_HEX + '|' + INTEGER_OCT + '|' + INTEGER_BIN + ')\z'
# @api public
#
class PNumericType < PScalarDataType
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'ScalarDataType',
'from' => { KEY_TYPE => POptionalType.new(PNumericType::DEFAULT), KEY_VALUE => nil },
'to' => { KEY_TYPE => POptionalType.new(PNumericType::DEFAULT), KEY_VALUE => nil })
end
def self.new_function(type)
@new_function ||= Puppet::Functions.create_loaded_function(:new_numeric, type.loader) do
local_types do
type "Convertible = Variant[Integer, Float, Boolean, Pattern[/#{FLOAT_PATTERN}/], Timespan, Timestamp]"
type 'NamedArgs = Struct[{from => Convertible, Optional[abs] => Boolean}]'
end
dispatch :from_args do
param 'Convertible', :from
optional_param 'Boolean', :abs
end
dispatch :from_hash do
param 'NamedArgs', :hash_args
end
argument_mismatch :on_error do
param 'Any', :from
optional_param 'Boolean', :abs
end
def from_args(from, abs = false)
result = from_convertible(from)
abs ? result.abs : result
end
def from_hash(args_hash)
from_args(args_hash['from'], args_hash['abs'] || false)
end
def from_convertible(from)
case from
when Float
from
when Integer
from
when Time::TimeData
from.to_f
when TrueClass
1
when FalseClass
0
else
begin
if from[0] == '0'
second_char = (from[1] || '').downcase
if second_char == 'b' || second_char == 'x'
# use built in conversion
return Integer(from)
end
end
Puppet::Pops::Utils.to_n(from)
rescue TypeError => e
raise TypeConversionError, e.message
rescue ArgumentError => e
raise TypeConversionError, e.message
end
end
end
def on_error(from, abs = false)
if from.is_a?(String)
_("The string '%{str}' cannot be converted to Numeric") % { str: from }
else
t = TypeCalculator.singleton.infer(from).generalize
_("Value of type %{type} cannot be converted to Numeric") % { type: t }
end
end
end
end
def initialize(from, to = Float::INFINITY)
from = -Float::INFINITY if from.nil? || from == :default
to = Float::INFINITY if to.nil? || to == :default
raise ArgumentError, "'from' must be less or equal to 'to'. Got (#{from}, #{to}" if from > to
@from = from
@to = to
end
# Checks if this numeric range intersects with another
#
# @param o [PNumericType] the range to compare with
# @return [Boolean] `true` if this range intersects with the other range
# @api public
def intersect?(o)
instance_of?(o.class) && !(@to < o.numeric_from || o.numeric_to < @from)
end
# Returns the lower bound of the numeric range or `nil` if no lower bound is set.
# @return [Float,Integer]
def from
@from == -Float::INFINITY ? nil : @from
end
# Returns the upper bound of the numeric range or `nil` if no upper bound is set.
# @return [Float,Integer]
def to
@to == Float::INFINITY ? nil : @to
end
# Same as #from but will return `-Float::Infinity` instead of `nil` if no lower bound is set.
# @return [Float,Integer]
def numeric_from
@from
end
# Same as #to but will return `Float::Infinity` instead of `nil` if no lower bound is set.
# @return [Float,Integer]
def numeric_to
@to
end
def hash
@from.hash ^ @to.hash
end
def eql?(o)
self.class == o.class && @from == o.numeric_from && @to == o.numeric_to
end
def instance?(o, guard = nil)
(o.is_a?(Float) || o.is_a?(Integer)) && o >= @from && o <= @to
end
def unbounded?
@from == -Float::INFINITY && @to == Float::INFINITY
end
protected
# @api_private
def _assignable?(o, guard)
return false unless o.is_a?(self.class)
# If o min and max are within the range of t
@from <= o.numeric_from && @to >= o.numeric_to
end
DEFAULT = PNumericType.new(-Float::INFINITY)
end
# @api public
#
class PIntegerType < PNumericType
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'NumericType')
end
# Will respond `true` for any range that is bounded at both ends.
#
# @return [Boolean] `true` if the type describes a finite range.
def finite_range?
@from != -Float::INFINITY && @to != Float::INFINITY
end
def generalize
DEFAULT
end
def instance?(o, guard = nil)
o.is_a?(Integer) && o >= numeric_from && o <= numeric_to
end
# Checks if this range is adjacent to the given range
#
# @param o [PIntegerType] the range to compare with
# @return [Boolean] `true` if this range is adjacent to the other range
# @api public
def adjacent?(o)
o.is_a?(PIntegerType) && (@to + 1 == o.from || o.to + 1 == @from)
end
# Concatenates this range with another range provided that the ranges intersect or
# are adjacent. When that's not the case, this method will return `nil`
#
# @param o [PIntegerType] the range to concatenate with this range
# @return [PIntegerType,nil] the concatenated range or `nil` when the ranges were apart
# @api public
def merge(o)
if intersect?(o) || adjacent?(o)
min = @from <= o.numeric_from ? @from : o.numeric_from
max = @to >= o.numeric_to ? @to : o.numeric_to
PIntegerType.new(min, max)
else
nil
end
end
def iterable?(guard = nil)
true
end
def iterable_type(guard = nil)
# It's unknown if the iterable will be a range (min, max) or a "times" (0, max)
PIterableType.new(PIntegerType::DEFAULT)
end
# Returns Float.Infinity if one end of the range is unbound
def size
return Float::INFINITY if @from == -Float::INFINITY || @to == Float::INFINITY
1 + (to - from).abs
end
# Returns the range as an array ordered so the smaller number is always first.
# The number may be Infinity or -Infinity.
def range
[@from, @to]
end
# Returns Enumerator if no block is given
# Returns nil if size is infinity (does not yield)
def each(&block)
r = Iterable.on(self)
block_given? ? r.each(&block) : r
end
# Returns a range where both to and from are positive numbers. Negative
# numbers are converted to zero
# @return [PIntegerType] a positive range
def to_size
if @from >= 0
self
else
PIntegerType.new(0, @to < 0 ? 0 : @to)
end
end
def new_function
@@new_function ||= Puppet::Functions.create_loaded_function(:new, loader) do
local_types do
type 'Radix = Variant[Default, Integer[2,2], Integer[8,8], Integer[10,10], Integer[16,16]]'
type "Convertible = Variant[Numeric, Boolean, Pattern[/#{INTEGER_PATTERN_LENIENT}/], Timespan, Timestamp]"
type 'NamedArgs = Struct[{from => Convertible, Optional[radix] => Radix, Optional[abs] => Boolean}]'
end
dispatch :from_args do
param 'Convertible', :from
optional_param 'Radix', :radix
optional_param 'Boolean', :abs
end
dispatch :from_hash do
param 'NamedArgs', :hash_args
end
argument_mismatch :on_error_hash do
param 'Hash', :hash_args
end
argument_mismatch :on_error do
param 'Any', :from
optional_param 'Integer', :radix
optional_param 'Boolean', :abs
end
def from_args(from, radix = :default, abs = false)
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/type_formatter.rb | lib/puppet/pops/types/type_formatter.rb | # frozen_string_literal: true
require_relative '../../../puppet/concurrent/thread_local_singleton'
module Puppet::Pops
module Types
# String
# ------
# Creates a string representation of a type.
#
# @api public
#
class TypeFormatter
extend Puppet::Concurrent::ThreadLocalSingleton
# Produces a String representation of the given type.
# @param t [PAnyType] the type to produce a string form
# @return [String] the type in string form
#
# @api public
#
def self.string(t)
singleton.string(t)
end
def initialize
@string_visitor = Visitor.new(nil, 'string', 0, 0)
end
def expanded
tf = clone
tf.instance_variable_set(:@expanded, true)
tf
end
def indented(indent = 0, indent_width = 2)
tf = clone
tf.instance_variable_set(:@indent, indent)
tf.instance_variable_set(:@indent_width, indent_width)
tf
end
def ruby(ref_ctor)
tf = clone
tf.instance_variable_set(:@ruby, true)
tf.instance_variable_set(:@ref_ctor, ref_ctor)
tf
end
# Produces a string representing the type
# @api public
#
def string(t)
@bld = ''.dup
append_string(t)
@bld
end
# Produces an string containing newline characters and indentation that represents the given
# type or literal _t_.
#
# @param t [Object] the type or literal to produce a string for
# @param indent [Integer] the current indentation level
# @param indent_width [Integer] the number of spaces to use for one indentation
#
# @api public
def indented_string(t, indent = 0, indent_width = 2)
@bld = ''.dup
append_indented_string(t, indent, indent_width)
@bld
end
# @api private
def append_indented_string(t, indent = 0, indent_width = 2, skip_initial_indent = false)
save_indent = @indent
save_indent_width = @indent_width
@indent = indent
@indent_width = indent_width
begin
(@indent * @indent_width).times { @bld << ' ' } unless skip_initial_indent
append_string(t)
@bld << "\n"
ensure
@indent = save_indent
@indent_width = save_indent_width
end
end
# @api private
def ruby_string(ref_ctor, indent, t)
@ruby = true
@ref_ctor = ref_ctor
begin
indented_string(t, indent)
ensure
@ruby = nil
@ref_ctor = nil
end
end
def append_default
@bld << 'default'
end
def append_string(t)
if @ruby && t.is_a?(PAnyType)
@ruby = false
begin
@bld << @ref_ctor << '('
@string_visitor.visit_this_0(self, TypeFormatter.new.string(t))
@bld << ')'
ensure
@ruby = true
end
else
@string_visitor.visit_this_0(self, t)
end
end
# Produces a string representing the type where type aliases have been expanded
# @api public
#
def alias_expanded_string(t)
@expanded = true
begin
string(t)
ensure
@expanded = false
end
end
# Produces a debug string representing the type (possibly with more information that the regular string format)
# @api public
#
def debug_string(t)
@debug = true
begin
string(t)
ensure
@debug = false
end
end
# @api private
def string_PAnyType(_); @bld << 'Any'; end
# @api private
def string_PUndefType(_); @bld << 'Undef'; end
# @api private
def string_PDefaultType(_); @bld << 'Default'; end
# @api private
def string_PBooleanType(t)
append_array('Boolean', t.value.nil?) { append_string(t.value) }
end
# @api private
def string_PScalarType(_); @bld << 'Scalar'; end
# @api private
def string_PScalarDataType(_); @bld << 'ScalarData'; end
# @api private
def string_PNumericType(_); @bld << 'Numeric'; end
# @api private
def string_PBinaryType(_); @bld << 'Binary'; end
# @api private
def string_PIntegerType(t)
append_array('Integer', t.unbounded?) { append_elements(range_array_part(t)) }
end
# @api private
def string_PTypeType(t)
append_array('Type', t.type.nil?) { append_string(t.type) }
end
# @api private
def string_PInitType(t)
append_array('Init', t.type.nil?) { append_strings([t.type, *t.init_args]) }
end
# @api private
def string_PIterableType(t)
append_array('Iterable', t.element_type.nil?) { append_string(t.element_type) }
end
# @api private
def string_PIteratorType(t)
append_array('Iterator', t.element_type.nil?) { append_string(t.element_type) }
end
# @api private
def string_PFloatType(t)
append_array('Float', t.unbounded?) { append_elements(range_array_part(t)) }
end
# @api private
def string_PRegexpType(t)
append_array('Regexp', t.pattern.nil?) { append_string(t.regexp) }
end
# @api private
def string_PStringType(t)
range = range_array_part(t.size_type)
append_array('String', range.empty? && !(@debug && !t.value.nil?)) do
if @debug
append_elements(range, !t.value.nil?)
append_string(t.value) unless t.value.nil?
else
append_elements(range)
end
end
end
# @api private
def string_PEnumType(t)
append_array('Enum', t.values.empty?) do
append_strings(t.values)
if t.case_insensitive?
@bld << COMMA_SEP
append_string(true)
end
end
end
# @api private
def string_PVariantType(t)
append_array('Variant', t.types.empty?) { append_strings(t.types) }
end
# @api private
def string_PSemVerType(t)
append_array('SemVer', t.ranges.empty?) { append_strings(t.ranges) }
end
# @api private
def string_PSemVerRangeType(t)
@bld << 'SemVerRange'
end
# @api private
def string_PTimestampType(t)
min = t.from
max = t.to
append_array('Timestamp', min.nil? && max.nil?) do
min.nil? ? append_default : append_string(min)
unless max.nil? || max == min
@bld << COMMA_SEP
append_string(max)
end
end
end
# @api private
def string_PTimespanType(t)
min = t.from
max = t.to
append_array('Timespan', min.nil? && max.nil?) do
min.nil? ? append_default : append_string(min)
unless max.nil? || max == min
@bld << COMMA_SEP
append_string(max)
end
end
end
# @api private
def string_PTupleType(t)
append_array('Tuple', t.types.empty?) do
append_strings(t.types, true)
append_elements(range_array_part(t.size_type), true)
chomp_list
end
end
# @api private
def string_PCallableType(t)
if t.return_type.nil?
append_array('Callable', t.param_types.nil?) { append_callable_params(t) }
elsif t.param_types.nil?
append_array('Callable', false) { append_strings([[], t.return_type], false) }
else
append_array('Callable', false) do
append_array('', false) { append_callable_params(t) }
@bld << COMMA_SEP
append_string(t.return_type)
end
end
end
def append_callable_params(t)
# translate to string, and skip Unit types
append_strings(t.param_types.types.reject { |t2| t2.instance_of?(PUnitType) }, true)
if t.param_types.types.empty?
append_strings([0, 0], true)
else
append_elements(range_array_part(t.param_types.size_type), true)
end
# Add block T last (after min, max) if present)
#
append_strings([t.block_type], true) unless t.block_type.nil?
chomp_list
end
# @api private
def string_PStructType(t)
append_array('Struct', t.elements.empty?) { append_hash(t.elements.to_h { |e| struct_element_pair(e) }) }
end
# @api private
def struct_element_pair(t)
k = t.key_type
value_optional = t.value_type.assignable?(PUndefType::DEFAULT)
if k.is_a?(POptionalType)
# Output as literal String
k = t.name if value_optional
else
k = value_optional ? PNotUndefType.new(k) : t.name
end
[k, t.value_type]
end
# @api private
def string_PPatternType(t)
append_array('Pattern', t.patterns.empty?) { append_strings(t.patterns.map(&:regexp)) }
end
# @api private
def string_PCollectionType(t)
range = range_array_part(t.size_type)
append_array('Collection', range.empty?) { append_elements(range) }
end
def string_Object(t)
type = TypeCalculator.infer(t)
if type.is_a?(PObjectTypeExtension)
type = type.base_type
end
if type.is_a?(PObjectType)
init_hash = type.extract_init_hash(t)
@bld << type.name << '('
if @indent
append_indented_string(init_hash, @indent, @indent_width, true)
@bld.chomp!
else
append_string(init_hash)
end
@bld << ')'
else
@bld << 'Instance of '
append_string(type)
end
end
def string_PuppetObject(t)
@bld << t._pcore_type.name << '('
if @indent
append_indented_string(t._pcore_init_hash, @indent, @indent_width, true)
@bld.chomp!
else
append_string(t._pcore_init_hash)
end
@bld << ')'
end
# @api private
def string_PURIType(t)
append_array('URI', t.parameters.nil?) { append_string(t._pcore_init_hash['parameters']) }
end
def string_URI(t)
@bld << 'URI('
if @indent
append_indented_string(t.to_s, @indent, @indent_width, true)
@bld.chomp!
else
append_string(t.to_s)
end
@bld << ')'
end
# @api private
def string_PUnitType(_)
@bld << 'Unit'
end
# @api private
def string_PRuntimeType(t)
append_array('Runtime', t.runtime.nil? && t.name_or_pattern.nil?) { append_strings([t.runtime, t.name_or_pattern]) }
end
# @api private
def string_PArrayType(t)
if t.has_empty_range?
append_array('Array') { append_strings([0, 0]) }
else
append_array('Array', t == PArrayType::DEFAULT) do
append_strings([t.element_type], true)
append_elements(range_array_part(t.size_type), true)
chomp_list
end
end
end
# @api private
def string_PHashType(t)
if t.has_empty_range?
append_array('Hash') { append_strings([0, 0]) }
else
append_array('Hash', t == PHashType::DEFAULT) do
append_strings([t.key_type, t.value_type], true)
append_elements(range_array_part(t.size_type), true)
chomp_list
end
end
end
# @api private
def string_PCatalogEntryType(_)
@bld << 'CatalogEntry'
end
# @api private
def string_PClassType(t)
append_array('Class', t.class_name.nil?) { append_elements([t.class_name]) }
end
# @api private
def string_PResourceType(t)
if t.type_name
append_array(capitalize_segments(t.type_name), t.title.nil?) { append_string(t.title) }
else
@bld << 'Resource'
end
end
# @api private
def string_PNotUndefType(t)
contained_type = t.type
append_array('NotUndef', contained_type.nil? || contained_type.instance_of?(PAnyType)) do
if contained_type.is_a?(PStringType) && !contained_type.value.nil?
append_string(contained_type.value)
else
append_string(contained_type)
end
end
end
# @api private
def string_PAnnotatedMember(m)
hash = m._pcore_init_hash
if hash.size == 1
string(m.type)
else
string(hash)
end
end
# Used when printing names of well known keys in an Object type. Placed in a separate
# method to allow override.
# @api private
def symbolic_key(key)
@ruby ? "'#{key}'" : key
end
# @api private
def string_PTypeSetType(t)
append_array('TypeSet') do
append_hash(t._pcore_init_hash.each, proc { |k| @bld << symbolic_key(k) }) do |k, v|
case k
when KEY_TYPES
old_ts = @type_set
@type_set = t
begin
append_hash(v, proc { |tk| @bld << symbolic_key(tk) }) do |_tk, tv|
if tv.is_a?(Hash)
append_object_hash(tv)
else
append_string(tv)
end
end
rescue
@type_set = old_ts
end
when KEY_REFERENCES
append_hash(v, proc { |tk| @bld << symbolic_key(tk) })
else
append_string(v)
end
end
end
end
# @api private
def string_PObjectType(t)
if @expanded
append_object_hash(t._pcore_init_hash(@type_set.nil? || !@type_set.defines_type?(t)))
else
@bld << (@type_set ? @type_set.name_for(t, t.label) : t.label)
end
end
def string_PObjectTypeExtension(t)
append_array(@type_set ? @type_set.name_for(t, t.name) : t.name, false) do
ips = t.init_parameters
if ips.is_a?(Array)
append_strings(ips)
else
append_string(ips)
end
end
end
# @api private
def string_PSensitiveType(t)
append_array('Sensitive', PAnyType::DEFAULT == t.type) { append_string(t.type) }
end
# @api private
def string_POptionalType(t)
optional_type = t.optional_type
append_array('Optional', optional_type.nil?) do
if optional_type.is_a?(PStringType) && !optional_type.value.nil?
append_string(optional_type.value)
else
append_string(optional_type)
end
end
end
# @api private
def string_PTypeAliasType(t)
expand = @expanded
if expand && t.self_recursion?
@guard ||= RecursionGuard.new
@guard.with_this(t) { |state| format_type_alias_type(t, (state & RecursionGuard::SELF_RECURSION_IN_THIS) == 0) }
else
format_type_alias_type(t, expand)
end
end
# @api private
def format_type_alias_type(t, expand)
if @type_set.nil?
@bld << t.name
if expand && !Loader::StaticLoader::BUILTIN_ALIASES.include?(t.name)
@bld << ' = '
append_string(t.resolved_type)
end
elsif expand && @type_set.defines_type?(t)
append_string(t.resolved_type)
else
@bld << @type_set.name_for(t, t.name)
end
end
# @api private
def string_PTypeReferenceType(t)
append_array('TypeReference') { append_string(t.type_string) }
end
# @api private
def string_Array(t)
append_array('') do
if @indent && !is_short_array?(t)
@indent += 1
t.each { |elem| newline; append_string(elem); @bld << COMMA_SEP }
chomp_list
@indent -= 1
newline
else
append_strings(t)
end
end
end
# @api private
def string_FalseClass(t); @bld << 'false'; end
# @api private
def string_Hash(t)
append_hash(t)
end
# @api private
def string_Module(t)
append_string(TypeCalculator.singleton.type(t))
end
# @api private
def string_NilClass(t); @bld << (@ruby ? 'nil' : 'undef'); end
# @api private
def string_Numeric(t); @bld << t.to_s; end
# @api private
def string_Regexp(t); @bld << PRegexpType.regexp_to_s_with_delimiters(t); end
# @api private
def string_String(t)
# Use single qoute on strings that does not contain single quotes, control characters, or backslashes.
@bld << StringConverter.singleton.puppet_quote(t)
end
# @api private
def string_Symbol(t); @bld << t.to_s; end
# @api private
def string_TrueClass(t); @bld << 'true'; end
# @api private
def string_Version(t); @bld << "'#{t}'"; end
# @api private
def string_VersionRange(t); @bld << "'#{t}'"; end
# @api private
def string_Timespan(t); @bld << "'#{t}'"; end
# @api private
def string_Timestamp(t); @bld << "'#{t}'"; end
# Debugging to_s to reduce the amount of output
def to_s
'[a TypeFormatter]'
end
NAME_SEGMENT_SEPARATOR = '::'
STARTS_WITH_ASCII_CAPITAL = /^[A-Z]/
# Capitalizes each segment in a name separated with the {NAME_SEPARATOR} conditionally. The name
# will not be subject to capitalization if it already starts with a capital letter. This to avoid
# that existing camel casing is lost.
#
# @param qualified_name [String] the name to capitalize
# @return [String] the capitalized name
#
# @api private
def capitalize_segments(qualified_name)
if !qualified_name.is_a?(String) || qualified_name =~ STARTS_WITH_ASCII_CAPITAL
qualified_name
else
segments = qualified_name.split(NAME_SEGMENT_SEPARATOR)
if segments.size == 1
qualified_name.capitalize
else
segments.each(&:capitalize!)
segments.join(NAME_SEGMENT_SEPARATOR)
end
end
end
private
COMMA_SEP = ', '
HASH_ENTRY_OP = ' => '
def is_short_array?(t)
t.empty? || 100 - @indent * @indent_width > t.inject(0) do |sum, elem|
case elem
when true, false, nil, Numeric, Symbol
sum + elem.inspect.length()
when String
sum + 2 + elem.length
when Hash, Array
sum + (elem.empty? ? 2 : 1000)
else
sum + 1000
end
end
end
def range_array_part(t)
if t.nil? || t.unbounded?
EMPTY_ARRAY
else
result = [t.from.nil? ? 'default' : t.from.to_s]
result << t.to.to_s unless t.to.nil?
result
end
end
def append_object_hash(hash)
@expanded = false
append_array('Object') do
append_hash(hash, proc { |k| @bld << symbolic_key(k) }) do |k, v|
case k
when KEY_ATTRIBUTES, KEY_FUNCTIONS
# Types might need to be output as type references
append_hash(v) do |_, fv|
if fv.is_a?(Hash)
append_hash(fv, proc { |fak| @bld << symbolic_key(fak) }) do |fak, fav|
case fak
when KEY_KIND
@bld << fav
else
append_string(fav)
end
end
else
append_string(fv)
end
end
when KEY_EQUALITY
append_array('') { append_strings(v) } if v.is_a?(Array)
else
append_string(v)
end
end
end
ensure
@expanded = true
end
def append_elements(array, to_be_continued = false)
case array.size
when 0
# do nothing
when 1
@bld << array[0]
@bld << COMMA_SEP if to_be_continued
else
array.each { |elem| @bld << elem << COMMA_SEP }
chomp_list unless to_be_continued
end
end
def append_strings(array, to_be_continued = false)
case array.size
when 0
# do nothing
when 1
append_string(array[0])
@bld << COMMA_SEP if to_be_continued
else
array.each do |elem|
append_string(elem)
@bld << COMMA_SEP
end
chomp_list unless to_be_continued
end
end
def append_array(start, empty = false)
@bld << start
unless empty
@bld << '['
yield
@bld << ']'
end
end
def append_hash(hash, key_proc = nil)
@bld << '{'
@indent += 1 if @indent
hash.each do |k, v|
newline if @indent
if key_proc.nil?
append_string(k)
else
key_proc.call(k)
end
@bld << HASH_ENTRY_OP
if block_given?
yield(k, v)
else
append_string(v)
end
@bld << COMMA_SEP
end
chomp_list
if @indent
@indent -= 1
newline
end
@bld << '}'
end
def newline
@bld.rstrip!
@bld << "\n"
(@indent * @indent_width).times { @bld << ' ' }
end
def chomp_list
@bld.chomp!(COMMA_SEP)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/type_mismatch_describer.rb | lib/puppet/pops/types/type_mismatch_describer.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
# @api private
class TypePathElement
attr_reader :key
def initialize(key)
@key = key
end
def hash
key.hash
end
def ==(o)
self.class == o.class && key == o.key
end
def eql?(o)
self == o
end
end
# @api private
class SubjectPathElement < TypePathElement
def to_s
key
end
end
# @api private
class EntryValuePathElement < TypePathElement
def to_s
"entry '#{key}'"
end
end
# @api private
class EntryKeyPathElement < TypePathElement
def to_s
"key of entry '#{key}'"
end
end
# @api private
class ParameterPathElement < TypePathElement
def to_s
"parameter '#{key}'"
end
end
# @api private
class ReturnTypeElement < TypePathElement
def initialize(name = 'return')
super(name)
end
def to_s
key
end
end
# @api private
class BlockPathElement < ParameterPathElement
def initialize(name = 'block')
super(name)
end
def to_s
key
end
end
# @api private
class ArrayPathElement < TypePathElement
def to_s
"index #{key}"
end
end
# @api private
class VariantPathElement < TypePathElement
def to_s
"variant #{key}"
end
end
# @api private
class SignaturePathElement < VariantPathElement
def to_s
"#{key + 1}."
end
end
# @api private
class Mismatch
attr_reader :path
def initialize(path)
@path = path || EMPTY_ARRAY
end
def canonical_path
@canonical_path ||= @path.reject { |e| e.is_a?(VariantPathElement) }
end
def message(variant, position)
"#{variant}unknown mismatch#{position}"
end
def merge(path, o)
self.class.new(path)
end
def ==(o)
self.class == o.class && canonical_path == o.canonical_path
end
def eql?(o)
self == o
end
def hash
canonical_path.hash
end
def chop_path(element_index)
return self if element_index >= @path.size
chopped_path = @path.clone
chopped_path.delete_at(element_index)
copy = clone
copy.instance_variable_set(:@path, chopped_path)
copy
end
def path_string
@path.join(' ')
end
def to_s
format
end
def format
p = @path
variant = ''
position = ''
unless p.empty?
f = p.first
if f.is_a?(SignaturePathElement)
variant = " #{f}"
p = p.drop(1)
end
position = " #{p.join(' ')}" unless p.empty?
end
message(variant, position)
end
end
# @abstract
# @api private
class KeyMismatch < Mismatch
attr_reader :key
def initialize(path, key)
super(path)
@key = key
end
def ==(o)
super.==(o) && key == o.key
end
def hash
super.hash ^ key.hash
end
end
# @api private
class MissingKey < KeyMismatch
def message(variant, position)
"#{variant}#{position} expects a value for key '#{key}'"
end
end
# @api private
class MissingParameter < KeyMismatch
def message(variant, position)
"#{variant}#{position} expects a value for parameter '#{key}'"
end
end
# @api private
class ExtraneousKey < KeyMismatch
def message(variant, position)
"#{variant}#{position} unrecognized key '#{@key}'"
end
end
# @api private
class InvalidParameter < ExtraneousKey
def message(variant, position)
"#{variant}#{position} has no parameter named '#{@key}'"
end
end
# @api private
class UnexpectedBlock < Mismatch
def message(variant, position)
"#{variant}#{position} does not expect a block"
end
end
# @api private
class MissingRequiredBlock < Mismatch
def message(variant, position)
"#{variant}#{position} expects a block"
end
end
# @api private
class UnresolvedTypeReference < Mismatch
attr_reader :unresolved
def initialize(path, unresolved)
super(path)
@unresolved = unresolved
end
def ==(o)
super.==(o) && @unresolved == o.unresolved
end
def hash
@unresolved.hash
end
def message(variant, position)
"#{variant}#{position} references an unresolved type '#{@unresolved}'"
end
end
# @api private
class ExpectedActualMismatch < Mismatch
attr_reader :expected, :actual
def initialize(path, expected, actual)
super(path)
@expected = (expected.is_a?(Array) ? PVariantType.maybe_create(expected) : expected).normalize
@actual = actual.normalize
end
def ==(o)
super.==(o) && expected == o.expected && actual == o.actual
end
def hash
[canonical_path, expected, actual].hash
end
end
# @api private
class TypeMismatch < ExpectedActualMismatch
include LabelProvider
# @return A new instance with the least restrictive respective boundaries
def merge(path, o)
self.class.new(path, [expected, o.expected].flatten.uniq, actual)
end
def message(variant, position)
e = expected
a = actual
multi = false
if e.is_a?(POptionalType)
e = e.optional_type
optional = true
end
if e.is_a?(PVariantType)
e = e.types
end
if e.is_a?(Array)
if report_detailed?(e, a)
a = detailed_actual_to_s(e, a)
e = e.map(&:to_alias_expanded_s)
else
e = e.map { |t| short_name(t) }.uniq
a = short_name(a)
end
e.insert(0, 'Undef') if optional
case e.size
when 1
e = e[0]
when 2
e = "#{e[0]} or #{e[1]}"
multi = true
else
e = "#{e[0..e.size - 2].join(', ')}, or #{e[e.size - 1]}"
multi = true
end
else
if report_detailed?(e, a)
a = detailed_actual_to_s(e, a)
e = e.to_alias_expanded_s
else
e = short_name(e)
a = short_name(a)
end
if optional
e = "Undef or #{e}"
multi = true
end
end
if multi
"#{variant}#{position} expects a value of type #{e}, got #{label(a)}"
else
"#{variant}#{position} expects #{a_an(e)} value, got #{label(a)}"
end
end
def label(o)
o.to_s
end
private
def short_name(t)
# Ensure that Optional, NotUndef, Sensitive, and Type are reported with included
# type parameter.
if t.is_a?(PTypeWithContainedType) && !(t.type.nil? || t.type.instance_of?(PAnyType))
"#{t.name}[#{t.type.name}]"
else
t.name.nil? ? t.simple_name : t.name
end
end
# Answers the question if `e` is a specialized type of `a`
# @param e [PAnyType] the expected type
# @param a [PAnyType] the actual type
# @return [Boolean] `true` when the _e_ is a specialization of _a_
#
def specialization(e, a)
case e
when PStructType
a.is_a?(PHashType)
when PTupleType
a.is_a?(PArrayType)
else
false
end
end
# Decides whether or not the report must be fully detailed, or if generalization can be permitted
# in the mismatch report. All comparisons are made using resolved aliases rather than the alias
# itself.
#
# @param e [PAnyType,Array[PAnyType]] the expected type or array of expected types
# @param a [PAnyType] the actual type
# @return [Boolean] `true` when the class of _a_ equals the class _e_ or,
# in case _e_ is an `Array`, the class of at least one element of _e_
def always_fully_detailed?(e, a)
if e.is_a?(Array)
e.any? { |t| always_fully_detailed?(t, a) }
else
e.instance_of?(a.class) || e.is_a?(PTypeAliasType) || a.is_a?(PTypeAliasType) || specialization(e, a)
end
end
# @param e [PAnyType,Array[PAnyType]] the expected type or array of expected types
# @param a [PAnyType] the actual type
# @return [Boolean] `true` when _a_ is assignable to _e_ or, in case _e_ is an `Array`,
# to at least one element of _e_
def any_assignable?(e, a)
e.is_a?(Array) ? e.any? { |t| t.assignable?(a) } : e.assignable?(a)
end
# @param e [PAnyType,Array[PAnyType]] the expected type or array of expected types
# @param a [PAnyType] the actual type
# @return [Boolean] `true` when _a_ is assignable to the default generalization of _e_ or,
# in case _e_ is an `Array`, to the default generalization of at least one element of _e_
def assignable_to_default?(e, a)
if e.is_a?(Array)
e.any? { |t| assignable_to_default?(t, a) }
else
e = e.resolved_type if e.is_a?(PTypeAliasType)
e.class::DEFAULT.assignable?(a)
end
end
# @param e [PAnyType,Array[PAnyType]] the expected type or array of expected types
# @param a [PAnyType] the actual type
# @return [Boolean] `true` when either #always_fully_detailed or #assignable_to_default returns `true`
def report_detailed?(e, a)
always_fully_detailed?(e, a) || assignable_to_default?(e, a)
end
# Returns its argument with all type aliases resolved
# @param e [PAnyType,Array[PAnyType]] the expected type or array of expected types
# @return [PAnyType,Array[PAnyType]] the resolved result
def all_resolved(e)
if e.is_a?(Array)
e.map { |t| all_resolved(t) }
else
e.is_a?(PTypeAliasType) ? all_resolved(e.resolved_type) : e
end
end
# Returns a string that either represents the generalized type _a_ or the type _a_ verbatim. The latter
# form is used when at least one of the following conditions are met:
#
# - #always_fully_detailed returns `true` for the resolved type of _e_ and _a_
# - #any_assignable? returns `true` for the resolved type of _e_ and the generalized type of _a_.
#
# @param e [PAnyType,Array[PAnyType]] the expected type or array of expected types
# @param a [PAnyType] the actual type
# @return [String] The string representation of the type _a_ or generalized type _a_
def detailed_actual_to_s(e, a)
e = all_resolved(e)
if always_fully_detailed?(e, a)
a.to_alias_expanded_s
else
any_assignable?(e, a.generalize) ? a.to_alias_expanded_s : a.simple_name
end
end
end
# @api private
class PatternMismatch < TypeMismatch
def message(variant, position)
e = expected
value_pfx = ''
if e.is_a?(POptionalType)
e = e.optional_type
value_pfx = 'an undef value or '
end
"#{variant}#{position} expects #{value_pfx}a match for #{e.to_alias_expanded_s}, got #{actual_string}"
end
def actual_string
a = actual
a.is_a?(PStringType) && !a.value.nil? ? "'#{a.value}'" : short_name(a)
end
end
# @api private
class SizeMismatch < ExpectedActualMismatch
def from
@expected.from || 0
end
def to
@expected.to || Float::INFINITY
end
# @return A new instance with the least restrictive respective boundaries
def merge(path, o)
range = PIntegerType.new(from < o.from ? from : o.from, to > o.to ? to : o.to)
self.class.new(path, range, @actual)
end
def message(variant, position)
"#{variant}#{position} expects size to be #{range_to_s(expected, '0')}, got #{range_to_s(actual, '0')}"
end
def range_to_s(range, zero_string)
min = range.from || 0
max = range.to || Float::INFINITY
if min == max
min == 0 ? zero_string : min.to_s
elsif min == 0
max == Float::INFINITY ? 'unlimited' : "at most #{max}"
elsif max == Float::INFINITY
"at least #{min}"
else
"between #{min} and #{max}"
end
end
end
# @api private
class CountMismatch < SizeMismatch
def message(variant, position)
min = expected.from || 0
max = expected.to || Float::INFINITY
suffix = min == 1 && (max == 1 || max == Float::INFINITY) || min == 0 && max == 1 ? '' : 's'
"#{variant}#{position} expects #{range_to_s(expected, 'no')} argument#{suffix}, got #{range_to_s(actual, 'none')}"
end
end
# @api private
class TypeMismatchDescriber
def self.validate_parameters(subject, params_struct, given_hash, missing_ok = false)
singleton.validate_parameters(subject, params_struct, given_hash, missing_ok)
end
def self.validate_default_parameter(subject, param_name, param_type, value)
singleton.validate_default_parameter(subject, param_name, param_type, value)
end
def self.describe_signatures(closure, signatures, args_tuple)
singleton.describe_signatures(closure, signatures, args_tuple)
end
def self.singleton
@singleton ||= new
end
def tense_deprecated
# TRANSLATORS TypeMismatchDescriber is a class name and 'tense' is a method name and should not be translated
message = _("Passing a 'tense' argument to the TypeMismatchDescriber is deprecated and ignored.")
message += ' ' + _("Everything is now reported using present tense")
Puppet.warn_once('deprecations', 'typemismatch#tense', message)
end
# Validates that all entries in the give_hash exists in the given param_struct, that their type conforms
# with the corresponding param_struct element and that all required values are provided.
#
# @param subject [String] string to be prepended to the exception message
# @param params_struct [PStructType] Struct to use for validation
# @param given_hash [Hash<String,Object>] the parameters to validate
# @param missing_ok [Boolean] Do not generate errors on missing parameters
# @param tense [Symbol] deprecated and ignored
#
def validate_parameters(subject, params_struct, given_hash, missing_ok = false, tense = :ignored)
tense_deprecated unless tense == :ignored
errors = describe_struct_signature(params_struct, given_hash, missing_ok).flatten
case errors.size
when 0
# do nothing
when 1
raise Puppet::ParseError, "#{subject}:#{errors[0].format}"
else
errors_str = errors.map(&:format).join("\n ")
raise Puppet::ParseError, "#{subject}:\n #{errors_str}"
end
end
# Describe a confirmed mismatch using present tense
#
# @param name [String] name of mismatch
# @param expected [PAnyType] expected type
# @param actual [PAnyType] actual type
# @param tense [Symbol] deprecated and ignored
#
def describe_mismatch(name, expected, actual, tense = :ignored)
tense_deprecated unless tense == :ignored
errors = describe(expected, actual, [SubjectPathElement.new(name)])
case errors.size
when 0
''
when 1
errors[0].format.strip
else
errors.map(&:format).join("\n ")
end
end
# @param subject [String] string to be prepended to the exception message
# @param param_name [String] parameter name
# @param param_type [PAnyType] parameter type
# @param value [Object] value to be validated against the given type
# @param tense [Symbol] deprecated and ignored
#
def validate_default_parameter(subject, param_name, param_type, value, tense = :ignored)
tense_deprecated unless tense == :ignored
unless param_type.instance?(value)
errors = describe(param_type, TypeCalculator.singleton.infer_set(value).generalize, [ParameterPathElement.new(param_name)])
case errors.size
when 0
# do nothing
when 1
raise Puppet::ParseError, "#{subject}:#{errors[0].format}"
else
errors_str = errors.map(&:format).join("\n ")
raise Puppet::ParseError, "#{subject}:\n #{errors_str}"
end
end
end
def get_deferred_function_return_type(value)
func = Puppet.lookup(:loaders).private_environment_loader
.load(:function, value.name)
dispatcher = func.class.dispatcher.find_matching_dispatcher(value.arguments)
raise ArgumentError, "No matching arity found for #{func.class.name} with arguments #{value.arguments}" unless dispatcher
dispatcher.type.return_type
end
private :get_deferred_function_return_type
# Validates that all entries in the _param_hash_ exists in the given param_struct, that their type conforms
# with the corresponding param_struct element and that all required values are provided.
# An error message is created for each problem found.
#
# @param params_struct [PStructType] Struct to use for validation
# @param param_hash [Hash<String,Object>] The parameters to validate
# @param missing_ok [Boolean] Do not generate errors on missing parameters
# @return [Array<Mismatch>] An array of found errors. An empty array indicates no errors.
def describe_struct_signature(params_struct, param_hash, missing_ok = false)
param_type_hash = params_struct.hashed_elements
result = param_hash.each_key.reject { |name| param_type_hash.include?(name) }.map { |name| InvalidParameter.new(nil, name) }
params_struct.elements.each do |elem|
name = elem.name
value = param_hash[name]
value_type = elem.value_type
if param_hash.include?(name)
if Puppet::Pops::Types::TypeFactory.deferred.implementation_class == value.class
if (df_return_type = get_deferred_function_return_type(value))
result << describe(value_type, df_return_type, [ParameterPathElement.new(name)]) unless value_type.generalize.assignable?(df_return_type.generalize)
else
warning_text = _("Deferred function %{function_name} has no return_type, unable to guarantee value type during compilation.") %
{ function_name: value.name }
Puppet.warn_once('deprecations',
"#{value.name}_deferred_warning",
warning_text)
end
else
result << describe(value_type, TypeCalculator.singleton.infer_set(value), [ParameterPathElement.new(name)]) unless value_type.instance?(value)
end
else
result << MissingParameter.new(nil, name) unless missing_ok || elem.key_type.is_a?(POptionalType)
end
end
result
end
def describe_signatures(closure, signatures, args_tuple, tense = :ignored)
tense_deprecated unless tense == :ignored
error_arrays = []
signatures.each_with_index do |signature, index|
error_arrays << describe_signature_arguments(signature, args_tuple, [SignaturePathElement.new(index)])
end
# Skip block checks if all signatures have argument errors
unless error_arrays.all? { |a| !a.empty? }
block_arrays = []
signatures.each_with_index do |signature, index|
block_arrays << describe_signature_block(signature, args_tuple, [SignaturePathElement.new(index)])
end
bc_count = block_arrays.count { |a| !a.empty? }
if bc_count == block_arrays.size
# Skip argument errors when all alternatives have block errors
error_arrays = block_arrays
elsif bc_count > 0
# Merge errors giving argument errors precedence over block errors
error_arrays.each_with_index { |a, index| error_arrays[index] = block_arrays[index] if a.empty? }
end
end
return nil if error_arrays.empty?
label = closure == 'lambda' ? 'block' : "'#{closure}'"
errors = merge_descriptions(0, CountMismatch, error_arrays)
if errors.size == 1
"#{label}#{errors[0].format}"
else
if signatures.size == 1
sig = signatures[0]
result = ["#{label} expects (#{signature_string(sig)})"]
result.concat(error_arrays[0].map { |e| " rejected:#{e.chop_path(0).format}" })
else
result = ["The function #{label} was called with arguments it does not accept. It expects one of:"]
signatures.each_with_index do |sg, index|
result << " (#{signature_string(sg)})"
result.concat(error_arrays[index].map { |e| " rejected:#{e.chop_path(0).format}" })
end
end
result.join("\n")
end
end
def describe_signature_arguments(signature, args_tuple, path)
params_tuple = signature.type.param_types
params_size_t = params_tuple.size_type || TypeFactory.range(*params_tuple.size_range)
case args_tuple
when PTupleType
arg_types = args_tuple.types
when PArrayType
arg_types = Array.new(params_tuple.types.size, args_tuple.element_type || PUndefType::DEFAULT)
else
return [TypeMismatch.new(path, params_tuple, args_tuple)]
end
if arg_types.last.kind_of_callable?
# Check other arguments
arg_count = arg_types.size - 1
describe_no_block_arguments(signature, arg_types, path, params_size_t, TypeFactory.range(arg_count, arg_count), arg_count)
else
args_size_t = TypeFactory.range(*args_tuple.size_range)
describe_no_block_arguments(signature, arg_types, path, params_size_t, args_size_t, arg_types.size)
end
end
def describe_signature_block(signature, args_tuple, path)
param_block_t = signature.block_type
arg_block_t = args_tuple.is_a?(PTupleType) ? args_tuple.types.last : nil
if TypeCalculator.is_kind_of_callable?(arg_block_t)
# Can't pass a block to a callable that doesn't accept one
if param_block_t.nil?
[UnexpectedBlock.new(path)]
else
# Check that the block is of the right type
describe(param_block_t, arg_block_t, path + [BlockPathElement.new])
end
elsif param_block_t.nil? || param_block_t.assignable?(PUndefType::DEFAULT)
# Check that the block is optional
EMPTY_ARRAY
else
[MissingRequiredBlock.new(path)]
end
end
def describe_no_block_arguments(signature, atypes, path, expected_size, actual_size, arg_count)
# not assignable if the number of types in actual is outside number of types in expected
if expected_size.assignable?(actual_size)
etypes = signature.type.param_types.types
enames = signature.parameter_names
arg_count.times do |index|
adx = index >= etypes.size ? etypes.size - 1 : index
etype = etypes[adx]
unless etype.assignable?(atypes[index])
descriptions = describe(etype, atypes[index], path + [ParameterPathElement.new(enames[adx])])
return descriptions unless descriptions.empty?
end
end
EMPTY_ARRAY
else
[CountMismatch.new(path, expected_size, actual_size)]
end
end
def describe_PVariantType(expected, original, actual, path)
variant_descriptions = []
types = expected.types
types = [PUndefType::DEFAULT] + types if original.is_a?(POptionalType)
types.each_with_index do |vt, index|
d = describe(vt, actual, path + [VariantPathElement.new(index)])
return EMPTY_ARRAY if d.empty?
variant_descriptions << d
end
descriptions = merge_descriptions(path.length, SizeMismatch, variant_descriptions)
if original.is_a?(PTypeAliasType) && descriptions.size == 1
# All variants failed in this alias so we report it as a mismatch on the alias
# rather than reporting individual failures of the variants
[TypeMismatch.new(path, original, actual)]
else
descriptions
end
end
def merge_descriptions(varying_path_position, size_mismatch_class, variant_descriptions)
descriptions = variant_descriptions.flatten
[size_mismatch_class, MissingRequiredBlock, UnexpectedBlock, TypeMismatch].each do |mismatch_class|
mismatches = descriptions.select { |desc| desc.is_a?(mismatch_class) }
next unless mismatches.size == variant_descriptions.size
# If they all have the same canonical path, then we can compact this into one
generic_mismatch = mismatches.inject do |prev, curr|
break nil unless prev.canonical_path == curr.canonical_path
prev.merge(prev.path, curr)
end
next if generic_mismatch.nil?
# Report the generic mismatch and skip the rest
descriptions = [generic_mismatch]
break
end
descriptions = descriptions.uniq
descriptions.size == 1 ? [descriptions[0].chop_path(varying_path_position)] : descriptions
end
def describe_POptionalType(expected, original, actual, path)
return EMPTY_ARRAY if actual.is_a?(PUndefType) || expected.optional_type.nil?
internal_describe(expected.optional_type, original.is_a?(PTypeAliasType) ? original : expected, actual, path)
end
def describe_PEnumType(expected, original, actual, path)
[PatternMismatch.new(path, original, actual)]
end
def describe_PPatternType(expected, original, actual, path)
[PatternMismatch.new(path, original, actual)]
end
def describe_PTypeAliasType(expected, original, actual, path)
internal_describe(expected.resolved_type.normalize, expected, actual, path)
end
def describe_PArrayType(expected, original, actual, path)
descriptions = []
element_type = expected.element_type || PAnyType::DEFAULT
case actual
when PTupleType
types = actual.types
expected_size = expected.size_type || PCollectionType::DEFAULT_SIZE
actual_size = actual.size_type || PIntegerType.new(types.size, types.size)
if expected_size.assignable?(actual_size)
types.each_with_index do |type, idx|
descriptions.concat(describe(element_type, type, path + [ArrayPathElement.new(idx)])) unless element_type.assignable?(type)
end
else
descriptions << SizeMismatch.new(path, expected_size, actual_size)
end
when PArrayType
expected_size = expected.size_type
actual_size = actual.size_type || PCollectionType::DEFAULT_SIZE
if expected_size.nil? || expected_size.assignable?(actual_size)
descriptions << TypeMismatch.new(path, original, PArrayType.new(actual.element_type))
else
descriptions << SizeMismatch.new(path, expected_size, actual_size)
end
else
descriptions << TypeMismatch.new(path, original, actual)
end
descriptions
end
def describe_PHashType(expected, original, actual, path)
descriptions = []
key_type = expected.key_type || PAnyType::DEFAULT
value_type = expected.value_type || PAnyType::DEFAULT
case actual
when PStructType
elements = actual.elements
expected_size = expected.size_type || PCollectionType::DEFAULT_SIZE
actual_size = PIntegerType.new(elements.count { |a| !a.key_type.assignable?(PUndefType::DEFAULT) }, elements.size)
if expected_size.assignable?(actual_size)
elements.each do |a|
descriptions.concat(describe(key_type, a.key_type, path + [EntryKeyPathElement.new(a.name)])) unless key_type.assignable?(a.key_type)
descriptions.concat(describe(value_type, a.value_type, path + [EntryValuePathElement.new(a.name)])) unless value_type.assignable?(a.value_type)
end
else
descriptions << SizeMismatch.new(path, expected_size, actual_size)
end
when PHashType
expected_size = expected.size_type
actual_size = actual.size_type || PCollectionType::DEFAULT_SIZE
if expected_size.nil? || expected_size.assignable?(actual_size)
descriptions << TypeMismatch.new(path, original, PHashType.new(actual.key_type, actual.value_type))
else
descriptions << SizeMismatch.new(path, expected_size, actual_size)
end
else
descriptions << TypeMismatch.new(path, original, actual)
end
descriptions
end
def describe_PStructType(expected, original, actual, path)
elements = expected.elements
descriptions = []
case actual
when PStructType
h2 = actual.hashed_elements.clone
elements.each do |e1|
key = e1.name
e2 = h2.delete(key)
if e2.nil?
descriptions << MissingKey.new(path, key) unless e1.key_type.assignable?(PUndefType::DEFAULT)
else
descriptions.concat(describe(e1.key_type, e2.key_type, path + [EntryKeyPathElement.new(key)])) unless e1.key_type.assignable?(e2.key_type)
descriptions.concat(describe(e1.value_type, e2.value_type, path + [EntryValuePathElement.new(key)])) unless e1.value_type.assignable?(e2.value_type)
end
end
h2.each_key { |key| descriptions << ExtraneousKey.new(path, key) }
when PHashType
actual_size = actual.size_type || PCollectionType::DEFAULT_SIZE
expected_size = PIntegerType.new(elements.count { |e| !e.key_type.assignable?(PUndefType::DEFAULT) }, elements.size)
if expected_size.assignable?(actual_size)
descriptions << TypeMismatch.new(path, original, PHashType.new(actual.key_type, actual.value_type))
else
descriptions << SizeMismatch.new(path, expected_size, actual_size)
end
else
descriptions << TypeMismatch.new(path, original, actual)
end
descriptions
end
def describe_PTupleType(expected, original, actual, path)
describe_tuple(expected, original, actual, path, SizeMismatch)
end
def describe_argument_tuple(expected, actual, path)
describe_tuple(expected, expected, actual, path, CountMismatch)
end
def describe_tuple(expected, original, actual, path, size_mismatch_class)
return EMPTY_ARRAY if expected == actual || expected.types.empty? && actual.is_a?(PArrayType)
expected_size = expected.size_type || TypeFactory.range(*expected.size_range)
case actual
when PTupleType
actual_size = actual.size_type || TypeFactory.range(*actual.size_range)
# not assignable if the number of types in actual is outside number of types in expected
if expected_size.assignable?(actual_size)
etypes = expected.types
descriptions = []
unless etypes.empty?
actual.types.each_with_index do |atype, index|
adx = index >= etypes.size ? etypes.size - 1 : index
descriptions.concat(describe(etypes[adx], atype, path + [ArrayPathElement.new(adx)]))
end
end
descriptions
else
[size_mismatch_class.new(path, expected_size, actual_size)]
end
when PArrayType
t2_entry = actual.element_type
if t2_entry.nil?
# Array of anything can not be assigned (unless tuple is tuple of anything) - this case
# was handled at the top of this method.
#
[TypeMismatch.new(path, original, actual)]
else
expected_size = expected.size_type || TypeFactory.range(*expected.size_range)
actual_size = actual.size_type || PCollectionType::DEFAULT_SIZE
if expected_size.assignable?(actual_size)
descriptions = []
expected.types.each_with_index do |etype, index|
descriptions.concat(describe(etype, actual.element_type, path + [ArrayPathElement.new(index)]))
end
descriptions
else
[size_mismatch_class.new(path, expected_size, actual_size)]
end
end
else
[TypeMismatch.new(path, original, actual)]
end
end
def describe_PCallableType(expected, original, actual, path)
if actual.is_a?(PCallableType)
# nil param_types means, any other Callable is assignable
if expected.param_types.nil? && expected.return_type.nil?
EMPTY_ARRAY
else
# NOTE: these tests are made in reverse as it is calling the callable that is constrained
# (it's lower bound), not its upper bound
param_errors = describe_argument_tuple(expected.param_types, actual.param_types, path)
if param_errors.empty?
this_return_t = expected.return_type || PAnyType::DEFAULT
that_return_t = actual.return_type || PAnyType::DEFAULT
if this_return_t.assignable?(that_return_t)
# names are ignored, they are just information
# Blocks must be compatible
this_block_t = expected.block_type || PUndefType::DEFAULT
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/type_acceptor.rb | lib/puppet/pops/types/type_acceptor.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
# Implements a standard visitor patter for the Puppet Type system.
#
# An instance of this module is passed as an argument to the {PAnyType#accept}
# method of a Type instance. That type will then use the {TypeAcceptor#visit} callback
# on the acceptor and then pass the acceptor to the `accept` method of all contained
# type instances so that the it gets a visit from each one recursively.
#
module TypeAcceptor
# @param type [PAnyType] the type that we accept a visit from
# @param guard [RecursionGuard] the guard against self recursion
def visit(type, guard)
end
end
# An acceptor that does nothing
class NoopTypeAcceptor
include TypeAcceptor
INSTANCE = NoopTypeAcceptor.new
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/p_timespan_type.rb | lib/puppet/pops/types/p_timespan_type.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
class PAbstractTimeDataType < PScalarType
# @param from [AbstractTime] lower bound for this type. Nil or :default means unbounded
# @param to [AbstractTime] upper bound for this type. Nil or :default means unbounded
def initialize(from, to = nil)
@from = convert_arg(from, true)
@to = convert_arg(to, false)
raise ArgumentError, "'from' must be less or equal to 'to'. Got (#{@from}, #{@to}" unless @from <= @to
end
# Checks if this numeric range intersects with another
#
# @param o [PNumericType] the range to compare with
# @return [Boolean] `true` if this range intersects with the other range
# @api public
def intersect?(o)
instance_of?(o.class) && !(@to < o.numeric_from || o.numeric_to < @from)
end
# Returns the lower bound of the numeric range or `nil` if no lower bound is set.
# @return [Float,Integer]
def from
@from == -Float::INFINITY ? nil : @from
end
# Returns the upper bound of the numeric range or `nil` if no upper bound is set.
# @return [Float,Integer]
def to
@to == Float::INFINITY ? nil : @to
end
# Same as #from but will return `-Float::Infinity` instead of `nil` if no lower bound is set.
# @return [Float,Integer]
def numeric_from
@from
end
# Same as #to but will return `Float::Infinity` instead of `nil` if no lower bound is set.
# @return [Float,Integer]
def numeric_to
@to
end
def hash
@from.hash ^ @to.hash
end
def eql?(o)
self.class == o.class && @from == o.numeric_from && @to == o.numeric_to
end
def unbounded?
@from == -Float::INFINITY && @to == Float::INFINITY
end
def convert_arg(arg, min)
case arg
when impl_class
arg
when Hash
impl_class.from_hash(arg)
when nil, :default
min ? -Float::INFINITY : Float::INFINITY
when String
impl_class.parse(arg)
when Integer
impl_class.new(arg * Time::NSECS_PER_SEC)
when Float
impl_class.new(arg * Time::NSECS_PER_SEC)
else
raise ArgumentError, "Unable to create a #{impl_class.name} from a #{arg.class.name}" unless arg.nil? || arg == :default
nil
end
end
# Concatenates this range with another range provided that the ranges intersect or
# are adjacent. When that's not the case, this method will return `nil`
#
# @param o [PAbstractTimeDataType] the range to concatenate with this range
# @return [PAbstractTimeDataType,nil] the concatenated range or `nil` when the ranges were apart
# @api public
def merge(o)
if intersect?(o) || adjacent?(o)
new_min = numeric_from <= o.numeric_from ? numeric_from : o.numeric_from
new_max = numeric_to >= o.numeric_to ? numeric_to : o.numeric_to
self.class.new(new_min, new_max)
else
nil
end
end
def _assignable?(o, guard)
instance_of?(o.class) && numeric_from <= o.numeric_from && numeric_to >= o.numeric_to
end
end
class PTimespanType < PAbstractTimeDataType
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'ScalarType',
'from' => { KEY_TYPE => POptionalType.new(PTimespanType::DEFAULT), KEY_VALUE => nil },
'to' => { KEY_TYPE => POptionalType.new(PTimespanType::DEFAULT), KEY_VALUE => nil })
end
def self.new_function(type)
@new_function ||= Puppet::Functions.create_loaded_function(:new_timespan, type.loader) do
local_types do
type 'Formats = Variant[String[2],Array[String[2], 1]]'
end
dispatch :from_seconds do
param 'Variant[Integer,Float]', :seconds
end
dispatch :from_string do
param 'String[1]', :string
optional_param 'Formats', :format
end
dispatch :from_fields do
param 'Integer', :days
param 'Integer', :hours
param 'Integer', :minutes
param 'Integer', :seconds
optional_param 'Integer', :milliseconds
optional_param 'Integer', :microseconds
optional_param 'Integer', :nanoseconds
end
dispatch :from_string_hash do
param <<-TYPE, :hash_arg
Struct[{
string => String[1],
Optional[format] => Formats
}]
TYPE
end
dispatch :from_fields_hash do
param <<-TYPE, :hash_arg
Struct[{
Optional[negative] => Boolean,
Optional[days] => Integer,
Optional[hours] => Integer,
Optional[minutes] => Integer,
Optional[seconds] => Integer,
Optional[milliseconds] => Integer,
Optional[microseconds] => Integer,
Optional[nanoseconds] => Integer
}]
TYPE
end
def from_seconds(seconds)
Time::Timespan.new((seconds * Time::NSECS_PER_SEC).to_i)
end
def from_string(string, format = Time::Timespan::Format::DEFAULTS)
Time::Timespan.parse(string, format)
end
def from_fields(days, hours, minutes, seconds, milliseconds = 0, microseconds = 0, nanoseconds = 0)
Time::Timespan.from_fields(false, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds)
end
def from_string_hash(args_hash)
Time::Timespan.from_string_hash(args_hash)
end
def from_fields_hash(args_hash)
Time::Timespan.from_fields_hash(args_hash)
end
end
end
def generalize
DEFAULT
end
def impl_class
Time::Timespan
end
def instance?(o, guard = nil)
o.is_a?(Time::Timespan) && o >= @from && o <= @to
end
DEFAULT = PTimespanType.new(nil, nil)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/p_sem_ver_range_type.rb | lib/puppet/pops/types/p_sem_ver_range_type.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
# An unparameterized type that represents all VersionRange instances
#
# @api public
class PSemVerRangeType < PAnyType
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'AnyType')
end
# Check if a version is included in a version range. The version can be a string or
# a `SemanticPuppet::SemVer`
#
# @param range [SemanticPuppet::VersionRange] the range to match against
# @param version [SemanticPuppet::Version,String] the version to match
# @return [Boolean] `true` if the range includes the given version
#
# @api public
def self.include?(range, version)
case version
when SemanticPuppet::Version
range.include?(version)
when String
begin
range.include?(SemanticPuppet::Version.parse(version))
rescue SemanticPuppet::Version::ValidationFailure
false
end
else
false
end
end
# Creates a {SemanticPuppet::VersionRange} from the given _version_range_ argument. If the argument is `nil` or
# a {SemanticPuppet::VersionRange}, it is returned. If it is a {String}, it will be parsed into a
# {SemanticPuppet::VersionRange}. Any other class will raise an {ArgumentError}.
#
# @param version_range [SemanticPuppet::VersionRange,String,nil] the version range to convert
# @return [SemanticPuppet::VersionRange] the converted version range
# @raise [ArgumentError] when the argument cannot be converted into a version range
#
def self.convert(version_range)
case version_range
when nil, SemanticPuppet::VersionRange
version_range
when String
SemanticPuppet::VersionRange.parse(version_range)
else
raise ArgumentError, "Unable to convert a #{version_range.class.name} to a SemVerRange"
end
end
# Checks if range _a_ is a sub-range of (i.e. completely covered by) range _b_
# @param a [SemanticPuppet::VersionRange] the first range
# @param b [SemanticPuppet::VersionRange] the second range
#
# @return [Boolean] `true` if _a_ is completely covered by _b_
def self.covered_by?(a, b)
b.begin <= a.begin && (b.end > a.end || b.end == a.end && (!b.exclude_end? || a.exclude_end?))
end
# Merge two ranges so that the result matches all versions matched by both. A merge
# is only possible when the ranges are either adjacent or have an overlap.
#
# @param a [SemanticPuppet::VersionRange] the first range
# @param b [SemanticPuppet::VersionRange] the second range
# @return [SemanticPuppet::VersionRange,nil] the result of the merge
#
# @api public
def self.merge(a, b)
if a.include?(b.begin) || b.include?(a.begin)
max = [a.end, b.end].max
exclude_end = false
if a.exclude_end?
exclude_end = max == a.end && (max > b.end || b.exclude_end?)
elsif b.exclude_end?
exclude_end = max == b.end && (max > a.end || a.exclude_end?)
end
SemanticPuppet::VersionRange.new([a.begin, b.begin].min, max, exclude_end)
elsif a.exclude_end? && a.end == b.begin
# Adjacent, a before b
SemanticPuppet::VersionRange.new(a.begin, b.end, b.exclude_end?)
elsif b.exclude_end? && b.end == a.begin
# Adjacent, b before a
SemanticPuppet::VersionRange.new(b.begin, a.end, a.exclude_end?)
else
# No overlap
nil
end
end
def roundtrip_with_string?
true
end
def instance?(o, guard = nil)
o.is_a?(SemanticPuppet::VersionRange)
end
def eql?(o)
self.class == o.class
end
def hash?
super ^ @version_range.hash
end
def self.new_function(type)
@new_function ||= Puppet::Functions.create_loaded_function(:new_VersionRange, type.loader) do
local_types do
type 'SemVerRangeString = String[1]'
type 'SemVerRangeHash = Struct[{min=>Variant[Default,SemVer],Optional[max]=>Variant[Default,SemVer],Optional[exclude_max]=>Boolean}]'
end
# Constructs a VersionRange from a String with a format specified by
#
# https://github.com/npm/node-semver#range-grammar
#
# The logical or || operator is not implemented since it effectively builds
# an array of ranges that may be disparate. The {{SemanticPuppet::VersionRange}} inherits
# from the standard ruby range. It must be possible to describe that range in terms
# of min, max, and exclude max.
#
# The Puppet Version type is parameterized and accepts multiple ranges so creating such
# constraints is still possible. It will just require several parameters rather than one
# parameter containing the '||' operator.
#
dispatch :from_string do
param 'SemVerRangeString', :str
end
# Constructs a VersionRange from a min, and a max version. The Boolean argument denotes
# whether or not the max version is excluded or included in the range. It is included by
# default.
#
dispatch :from_versions do
param 'Variant[Default,SemVer]', :min
param 'Variant[Default,SemVer]', :max
optional_param 'Boolean', :exclude_max
end
# Same as #from_versions but each argument is instead given in a Hash
#
dispatch :from_hash do
param 'SemVerRangeHash', :hash_args
end
def from_string(str)
SemanticPuppet::VersionRange.parse(str)
end
def from_versions(min, max = :default, exclude_max = false)
min = SemanticPuppet::Version::MIN if min == :default
max = SemanticPuppet::Version::MAX if max == :default
SemanticPuppet::VersionRange.new(min, max, exclude_max)
end
def from_hash(hash)
from_versions(hash['min'], hash.fetch('max', :default), hash.fetch('exclude_max', false))
end
end
end
DEFAULT = PSemVerRangeType.new
protected
def _assignable?(o, guard)
self == o
end
def self.range_pattern
part = '(?<part>[0-9A-Za-z-]+)'
parts = "(?<parts>#{part}(?:\\.\\g<part>)*)"
qualifier = "(?:-#{parts})?(?:\\+\\g<parts>)?"
xr = '(?<xr>[xX*]|0|[1-9][0-9]*)'
partial = "(?<partial>#{xr}(?:\\.\\g<xr>(?:\\.\\g<xr>#{qualifier})?)?)"
hyphen = "(?:#{partial}\\s+-\\s+\\g<partial>)"
simple = "(?<simple>(?:<|>|>=|<=|~|\\^)?\\g<partial>)"
"#{hyphen}|#{simple}(?:\\s+\\g<simple>)*"
end
private_class_method :range_pattern
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/type_set_reference.rb | lib/puppet/pops/types/type_set_reference.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
class TypeSetReference
include Annotatable
attr_reader :name_authority
attr_reader :name
attr_reader :version_range
attr_reader :type_set
def initialize(owner, init_hash)
@owner = owner
@name_authority = (init_hash[KEY_NAME_AUTHORITY] || owner.name_authority).freeze
@name = init_hash[KEY_NAME].freeze
@version_range = PSemVerRangeType.convert(init_hash[KEY_VERSION_RANGE])
init_annotatable(init_hash)
end
def accept(visitor, guard)
annotatable_accept(visitor, guard)
end
def eql?(o)
self.class == o.class && @name_authority.eql?(o.name_authority) && @name.eql?(o.name) && @version_range.eql?(o.version_range)
end
def hash
[@name_authority, @name, @version_range].hash
end
def _pcore_init_hash
result = super
result[KEY_NAME_AUTHORITY] = @name_authority unless @name_authority == @owner.name_authority
result[KEY_NAME] = @name
result[KEY_VERSION_RANGE] = @version_range.to_s
result
end
def resolve(loader)
typed_name = Loader::TypedName.new(:type, @name, @name_authority)
loaded_entry = loader.load_typed(typed_name)
type_set = loaded_entry.nil? ? nil : loaded_entry.value
raise ArgumentError, "#{self} cannot be resolved" if type_set.nil?
raise ArgumentError, "#{self} resolves to a #{type_set.name}" unless type_set.is_a?(PTypeSetType)
@type_set = type_set.resolve(loader)
unless @version_range.include?(@type_set.version)
raise ArgumentError, "#{self} resolves to an incompatible version. Expected #{@version_range}, got #{type_set.version}"
end
nil
end
def to_s
"#{@owner.label} reference to TypeSet named '#{@name}'"
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/type_calculator.rb | lib/puppet/pops/types/type_calculator.rb | # frozen_string_literal: true
require_relative '../../../puppet/concurrent/thread_local_singleton'
module Puppet::Pops
module Types
# The TypeCalculator can answer questions about puppet types.
#
# The Puppet type system is primarily based on sub-classing. When asking the type calculator to infer types from Ruby in general, it
# may not provide the wanted answer; it does not for instance take module inclusions and extensions into account. In general the type
# system should be unsurprising for anyone being exposed to the notion of type. The type `Data` may require a bit more explanation; this
# is an abstract type that includes all scalar types, as well as Array with an element type compatible with Data, and Hash with key
# compatible with scalar and elements compatible with Data. Expressed differently; Data is what you typically express using JSON (with
# the exception that the Puppet type system also includes Pattern (regular expression) as a scalar.
#
# Inference
# ---------
# The `infer(o)` method infers a Puppet type for scalar Ruby objects, and for Arrays and Hashes.
# The inference result is instance specific for single typed collections
# and allows answering questions about its embedded type. It does not however preserve multiple types in
# a collection, and can thus not answer questions like `[1,a].infer() =~ Array[Integer, String]` since the inference
# computes the common type Scalar when combining Integer and String.
#
# The `infer_generic(o)` method infers a generic Puppet type for scalar Ruby object, Arrays and Hashes.
# This inference result does not contain instance specific information; e.g. Array[Integer] where the integer
# range is the generic default. Just `infer` it also combines types into a common type.
#
# The `infer_set(o)` method works like `infer` but preserves all type information. It does not do any
# reduction into common types or ranges. This method of inference is best suited for answering questions
# about an object being an instance of a type. It correctly answers: `[1,a].infer_set() =~ Array[Integer, String]`
#
# The `generalize!(t)` method modifies an instance specific inference result to a generic. The method mutates
# the given argument. Basically, this removes string instances from String, and range from Integer and Float.
#
# Assignability
# -------------
# The `assignable?(t1, t2)` method answers if t2 conforms to t1. The type t2 may be an instance, in which case
# its type is inferred, or a type.
#
# Instance?
# ---------
# The `instance?(t, o)` method answers if the given object (instance) is an instance that is assignable to the given type.
#
# String
# ------
# Creates a string representation of a type.
#
# Creation of Type instances
# --------------------------
# Instance of the classes in the {Types type model} are used to denote a specific type. It is most convenient
# to use the {TypeFactory} when creating instances.
#
# @note
# In general, new instances of the wanted type should be created as they are assigned to models using containment, and a
# contained object can only be in one container at a time. Also, the type system may include more details in each type
# instance, such as if it may be nil, be empty, contain a certain count etc. Or put differently, the puppet types are not
# singletons.
#
# All types support `copy` which should be used when assigning a type where it is unknown if it is bound or not
# to a parent type. A check can be made with `t.eContainer().nil?`
#
# Equality and Hash
# -----------------
# Type instances are equal in terms of Ruby eql? and `==` if they describe the same type, but they are not `equal?` if they are not
# the same type instance. Two types that describe the same type have identical hash - this makes them usable as hash keys.
#
# Types and Subclasses
# --------------------
# In general, the type calculator should be used to answer questions if a type is a subtype of another (using {#assignable?}, or
# {#instance?} if the question is if a given object is an instance of a given type (or is a subtype thereof).
# Many of the types also have a Ruby subtype relationship; e.g. PHashType and PArrayType are both subtypes of PCollectionType, and
# PIntegerType, PFloatType, PStringType,... are subtypes of PScalarType. Even if it is possible to answer certain questions about
# type by looking at the Ruby class of the types this is considered an implementation detail, and such checks should in general
# be performed by the type_calculator which implements the type system semantics.
#
# The PRuntimeType
# -------------
# The PRuntimeType corresponds to a type in the runtime system (currently only supported runtime is 'ruby'). The
# type has a runtime_type_name that corresponds to a Ruby Class name.
# A Runtime[ruby] type can be used to describe any ruby class except for the puppet types that are specialized
# (i.e. PRuntimeType should not be used for Integer, String, etc. since there are specialized types for those).
# When the type calculator deals with PRuntimeTypes and checks for assignability, it determines the
# "common ancestor class" of two classes.
# This check is made based on the superclasses of the two classes being compared. In order to perform this, the
# classes must be present (i.e. they are resolved from the string form in the PRuntimeType to a
# loaded, instantiated Ruby Class). In general this is not a problem, since the question to produce the common
# super type for two objects means that the classes must be present or there would have been
# no instances present in the first place. If however the classes are not present, the type
# calculator will fall back and state that the two types at least have Any in common.
#
# @see TypeFactory for how to create instances of types
# @see TypeParser how to construct a type instance from a String
# @see Types for details about the type model
#
# Using the Type Calculator
# -----
# The type calculator can be directly used via its class methods. If doing time critical work and doing many
# calls to the type calculator, it is more performant to create an instance and invoke the corresponding
# instance methods. Note that inference is an expensive operation, rather than inferring the same thing
# several times, it is in general better to infer once and then copy the result if mutation to a more generic form is
# required.
#
# @api public
#
class TypeCalculator
extend Puppet::Concurrent::ThreadLocalSingleton
# @api public
def self.assignable?(t1, t2)
singleton.assignable?(t1, t2)
end
# Answers, does the given callable accept the arguments given in args (an array or a tuple)
# @param callable [PCallableType] - the callable
# @param args [PArrayType, PTupleType] args optionally including a lambda callable at the end
# @return [Boolean] true if the callable accepts the arguments
#
# @api public
def self.callable?(callable, args)
singleton.callable?(callable, args)
end
# @api public
def self.infer(o)
singleton.infer(o)
end
# Infers a type if given object may have callable members, else returns nil.
# Caller must check for nil or if returned type supports members.
# This is a much cheaper call than doing a call to the general infer(o) method.
#
# @api private
def self.infer_callable_methods_t(o)
# If being a value that cannot have Pcore based methods callable from Puppet Language
if o.is_a?(String) ||
o.is_a?(Numeric) ||
o.is_a?(TrueClass) ||
o.is_a?(FalseClass) ||
o.is_a?(Regexp) ||
o.instance_of?(Array) ||
o.instance_of?(Hash) ||
Types::PUndefType::DEFAULT.instance?(o)
return nil
end
# For other objects (e.g. PObjectType instances, and runtime types) full inference needed, since that will
# cover looking into the runtime type registry.
#
infer(o)
end
# @api public
def self.generalize(o)
singleton.generalize(o)
end
# @api public
def self.infer_set(o)
singleton.infer_set(o)
end
# @api public
def self.iterable(t)
singleton.iterable(t)
end
# @api public
#
def initialize
@infer_visitor = Visitor.new(nil, 'infer', 0, 0)
@extract_visitor = Visitor.new(nil, 'extract', 0, 0)
end
# Answers 'can an instance of type t2 be assigned to a variable of type t'.
# Does not accept nil/undef unless the type accepts it.
#
# @api public
#
def assignable?(t, t2)
if t.is_a?(Module)
t = type(t)
end
t.is_a?(PAnyType) ? t.assignable?(t2) : false
end
# Returns an iterable if the t represents something that can be iterated
def iterable(t)
# Create an iterable on the type if possible
Iterable.on(t)
end
# Answers, does the given callable accept the arguments given in args (an array or a tuple)
#
def callable?(callable, args)
callable.is_a?(PAnyType) && callable.callable?(args)
end
# Answers if the two given types describe the same type
def equals(left, right)
return false unless left.is_a?(PAnyType) && right.is_a?(PAnyType)
# Types compare per class only - an extra test must be made if the are mutually assignable
# to find all types that represent the same type of instance
#
left == right || (assignable?(right, left) && assignable?(left, right))
end
# Answers 'what is the Puppet Type corresponding to the given Ruby class'
# @param c [Module] the class for which a puppet type is wanted
# @api public
#
def type(c)
raise ArgumentError, 'Argument must be a Module' unless c.is_a? Module
# Can't use a visitor here since we don't have an instance of the class
if c <= Integer
type = PIntegerType::DEFAULT
elsif c == Float
type = PFloatType::DEFAULT
elsif c == Numeric
type = PNumericType::DEFAULT
elsif c == String
type = PStringType::DEFAULT
elsif c == Regexp
type = PRegexpType::DEFAULT
elsif c == NilClass
type = PUndefType::DEFAULT
elsif c == FalseClass || c == TrueClass
type = PBooleanType::DEFAULT
elsif c == Class
type = PTypeType::DEFAULT
elsif c == Array
# Assume array of any
type = PArrayType::DEFAULT
elsif c == Hash
# Assume hash of any
type = PHashType::DEFAULT
else
type = PRuntimeType.new(:ruby, c.name)
end
type
end
# Generalizes value specific types. The generalized type is returned.
# @api public
def generalize(o)
o.is_a?(PAnyType) ? o.generalize : o
end
# Answers 'what is the single common Puppet Type describing o', or if o is an Array or Hash, what is the
# single common type of the elements (or keys and elements for a Hash).
# @api public
#
def infer(o)
# Optimize the most common cases into direct calls.
# Explicit if/elsif/else is faster than case
case o
when String
infer_String(o)
when Integer # need subclasses for Ruby < 2.4
infer_Integer(o)
when Array
infer_Array(o)
when Hash
infer_Hash(o)
when Evaluator::PuppetProc
infer_PuppetProc(o)
else
@infer_visitor.visit_this_0(self, o)
end
end
def infer_generic(o)
generalize(infer(o))
end
# Answers 'what is the set of Puppet Types of o'
# @api public
#
def infer_set(o)
if o.instance_of?(Array)
infer_set_Array(o)
elsif o.instance_of?(Hash)
infer_set_Hash(o)
elsif o.instance_of?(SemanticPuppet::Version)
infer_set_Version(o)
else
infer(o)
end
end
# Answers 'is o an instance of type t'
# @api public
#
def self.instance?(t, o)
singleton.instance?(t, o)
end
# Answers 'is o an instance of type t'
# @api public
#
def instance?(t, o)
if t.is_a?(Module)
t = type(t)
end
t.is_a?(PAnyType) ? t.instance?(o) : false
end
# Answers if t is a puppet type
# @api public
#
def is_ptype?(t)
t.is_a?(PAnyType)
end
# Answers if t represents the puppet type PUndefType
# @api public
#
def is_pnil?(t)
t.nil? || t.is_a?(PUndefType)
end
# Answers, 'What is the common type of t1 and t2?'
#
# TODO: The current implementation should be optimized for performance
#
# @api public
#
def common_type(t1, t2)
raise ArgumentError, 'two types expected' unless (is_ptype?(t1) || is_pnil?(t1)) && (is_ptype?(t2) || is_pnil?(t2))
# TODO: This is not right since Scalar U Undef is Any
# if either is nil, the common type is the other
if is_pnil?(t1)
return t2
elsif is_pnil?(t2)
return t1
end
# If either side is Unit, it is the other type
if t1.is_a?(PUnitType)
return t2
elsif t2.is_a?(PUnitType)
return t1
end
# Simple case, one is assignable to the other
if assignable?(t1, t2)
return t1
elsif assignable?(t2, t1)
return t2
end
# when both are arrays, return an array with common element type
if t1.is_a?(PArrayType) && t2.is_a?(PArrayType)
return PArrayType.new(common_type(t1.element_type, t2.element_type))
end
# when both are hashes, return a hash with common key- and element type
if t1.is_a?(PHashType) && t2.is_a?(PHashType)
key_type = common_type(t1.key_type, t2.key_type)
value_type = common_type(t1.value_type, t2.value_type)
return PHashType.new(key_type, value_type)
end
# when both are host-classes, reduce to PHostClass[] (since one was not assignable to the other)
if t1.is_a?(PClassType) && t2.is_a?(PClassType)
return PClassType::DEFAULT
end
# when both are resources, reduce to Resource[T] or Resource[] (since one was not assignable to the other)
if t1.is_a?(PResourceType) && t2.is_a?(PResourceType)
# only Resource[] unless the type name is the same
return t1.type_name == t2.type_name ? PResourceType.new(t1.type_name, nil) : PResourceType::DEFAULT
end
# Integers have range, expand the range to the common range
if t1.is_a?(PIntegerType) && t2.is_a?(PIntegerType)
return PIntegerType.new([t1.numeric_from, t2.numeric_from].min, [t1.numeric_to, t2.numeric_to].max)
end
# Floats have range, expand the range to the common range
if t1.is_a?(PFloatType) && t2.is_a?(PFloatType)
return PFloatType.new([t1.numeric_from, t2.numeric_from].min, [t1.numeric_to, t2.numeric_to].max)
end
if t1.is_a?(PStringType) && (t2.is_a?(PStringType) || t2.is_a?(PEnumType))
if t2.is_a?(PEnumType)
return t1.value.nil? ? PEnumType::DEFAULT : PEnumType.new(t2.values | [t1.value])
end
if t1.size_type.nil? || t2.size_type.nil?
return t1.value.nil? || t2.value.nil? ? PStringType::DEFAULT : PEnumType.new([t1.value, t2.value])
end
return PStringType.new(common_type(t1.size_type, t2.size_type))
end
if t1.is_a?(PPatternType) && t2.is_a?(PPatternType)
return PPatternType.new(t1.patterns | t2.patterns)
end
if t1.is_a?(PEnumType) && (t2.is_a?(PStringType) || t2.is_a?(PEnumType))
# The common type is one that complies with either set
if t2.is_a?(PEnumType)
return PEnumType.new(t1.values | t2.values)
end
return t2.value.nil? ? PEnumType::DEFAULT : PEnumType.new(t1.values | [t2.value])
end
if t1.is_a?(PVariantType) && t2.is_a?(PVariantType)
# The common type is one that complies with either set
return PVariantType.maybe_create(t1.types | t2.types)
end
if t1.is_a?(PRegexpType) && t2.is_a?(PRegexpType)
# if they were identical, the general rule would return a parameterized regexp
# since they were not, the result is a generic regexp type
return PRegexpType::DEFAULT
end
if t1.is_a?(PCallableType) && t2.is_a?(PCallableType)
# They do not have the same signature, and one is not assignable to the other,
# what remains is the most general form of Callable
return PCallableType::DEFAULT
end
# Common abstract types, from most specific to most general
if common_numeric?(t1, t2)
return PNumericType::DEFAULT
end
if common_scalar_data?(t1, t2)
return PScalarDataType::DEFAULT
end
if common_scalar?(t1, t2)
return PScalarType::DEFAULT
end
if common_data?(t1, t2)
return TypeFactory.data
end
# Meta types Type[Integer] + Type[String] => Type[Data]
if t1.is_a?(PTypeType) && t2.is_a?(PTypeType)
return PTypeType.new(common_type(t1.type, t2.type))
end
if common_rich_data?(t1, t2)
return TypeFactory.rich_data
end
# If both are Runtime types
if t1.is_a?(PRuntimeType) && t2.is_a?(PRuntimeType)
if t1.runtime == t2.runtime && t1.runtime_type_name == t2.runtime_type_name
return t1
end
# finding the common super class requires that names are resolved to class
# NOTE: This only supports runtime type of :ruby
c1 = ClassLoader.provide_from_type(t1)
c2 = ClassLoader.provide_from_type(t2)
if c1 && c2
c2_superclasses = superclasses(c2)
superclasses(c1).each do |c1_super|
c2_superclasses.each do |c2_super|
if c1_super == c2_super
return PRuntimeType.new(:ruby, c1_super.name)
end
end
end
end
end
# They better both be Any type, or the wrong thing was asked and nil is returned
t1.is_a?(PAnyType) && t2.is_a?(PAnyType) ? PAnyType::DEFAULT : nil
end
# Produces the superclasses of the given class, including the class
def superclasses(c)
result = [c]
while s = c.superclass # rubocop:disable Lint/AssignmentInCondition
result << s
c = s
end
result
end
# Reduces an enumerable of types to a single common type.
# @api public
#
def reduce_type(enumerable)
enumerable.reduce(nil) { |memo, t| common_type(memo, t) }
end
# Reduce an enumerable of objects to a single common type
# @api public
#
def infer_and_reduce_type(enumerable)
reduce_type(enumerable.map { |o| infer(o) })
end
# The type of all modules is PTypeType
# @api private
#
def infer_Module(o)
PTypeType.new(PRuntimeType.new(:ruby, o.name))
end
# @api private
def infer_Closure(o)
o.type
end
# @api private
def infer_Iterator(o)
PIteratorType.new(o.element_type)
end
# @api private
def infer_Function(o)
o.class.dispatcher.to_type
end
# @api private
def infer_Object(o)
if o.is_a?(PuppetObject)
o._pcore_type
else
name = o.class.name
return PRuntimeType.new(:ruby, nil) if name.nil? # anonymous class that doesn't implement PuppetObject is impossible to infer
ir = Loaders.implementation_registry
type = ir.nil? ? nil : ir.type_for_module(name)
return PRuntimeType.new(:ruby, name) if type.nil?
if type.is_a?(PObjectType) && type.parameterized?
type = PObjectTypeExtension.create_from_instance(type, o)
end
type
end
end
# The type of all types is PTypeType
# @api private
#
def infer_PAnyType(o)
PTypeType.new(o)
end
# The type of all types is PTypeType
# This is the metatype short circuit.
# @api private
#
def infer_PTypeType(o)
PTypeType.new(o)
end
# @api private
def infer_String(o)
PStringType.new(o)
end
# @api private
def infer_Float(o)
PFloatType.new(o, o)
end
# @api private
def infer_Integer(o)
PIntegerType.new(o, o)
end
# @api private
def infer_Regexp(o)
PRegexpType.new(o)
end
# @api private
def infer_NilClass(o)
PUndefType::DEFAULT
end
# @api private
# @param o [Proc]
def infer_Proc(o)
min = 0
max = 0
mapped_types = o.parameters.map do |p|
case p[0]
when :rest
max = :default
break PAnyType::DEFAULT
when :req
min += 1
end
max += 1
PAnyType::DEFAULT
end
param_types = Types::PTupleType.new(mapped_types, Types::PIntegerType.new(min, max))
Types::PCallableType.new(param_types)
end
# @api private
def infer_PuppetProc(o)
infer_Closure(o.closure)
end
# Inference of :default as PDefaultType, and all other are Ruby[Symbol]
# @api private
def infer_Symbol(o)
case o
when :default
PDefaultType::DEFAULT
when :undef
PUndefType::DEFAULT
else
infer_Object(o)
end
end
# @api private
def infer_Sensitive(o)
PSensitiveType.new(infer(o.unwrap))
end
# @api private
def infer_Timespan(o)
PTimespanType.new(o, o)
end
# @api private
def infer_Timestamp(o)
PTimestampType.new(o, o)
end
# @api private
def infer_TrueClass(o)
PBooleanType::TRUE
end
# @api private
def infer_FalseClass(o)
PBooleanType::FALSE
end
# @api private
def infer_URI(o)
PURIType.new(o)
end
# @api private
# A Puppet::Parser::Resource, or Puppet::Resource
#
def infer_Resource(o)
# Only Puppet::Resource can have a title that is a symbol :undef, a PResource cannot.
# A mapping must be made to empty string. A nil value will result in an error later
title = o.title
title = '' if :undef == title
PTypeType.new(PResourceType.new(o.type.to_s, title))
end
# @api private
def infer_Array(o)
if o.instance_of?(Array)
if o.empty?
PArrayType::EMPTY
else
PArrayType.new(infer_and_reduce_type(o), size_as_type(o))
end
else
infer_Object(o)
end
end
# @api private
def infer_Binary(o)
PBinaryType::DEFAULT
end
# @api private
def infer_Version(o)
PSemVerType::DEFAULT
end
# @api private
def infer_VersionRange(o)
PSemVerRangeType::DEFAULT
end
# @api private
def infer_Hash(o)
if o.instance_of?(Hash)
if o.empty?
PHashType::EMPTY
else
ktype = infer_and_reduce_type(o.keys)
etype = infer_and_reduce_type(o.values)
PHashType.new(ktype, etype, size_as_type(o))
end
else
infer_Object(o)
end
end
def size_as_type(collection)
size = collection.size
PIntegerType.new(size, size)
end
# Common case for everything that intrinsically only has a single type
def infer_set_Object(o)
infer(o)
end
def infer_set_Array(o)
if o.empty?
PArrayType::EMPTY
else
PTupleType.new(o.map { |x| infer_set(x) })
end
end
def infer_set_Hash(o)
if o.empty?
PHashType::EMPTY
elsif o.keys.all? { |k| PStringType::NON_EMPTY.instance?(k) }
PStructType.new(o.each_pair.map { |k, v| PStructElement.new(PStringType.new(k), infer_set(v)) })
else
ktype = PVariantType.maybe_create(o.keys.map { |k| infer_set(k) })
etype = PVariantType.maybe_create(o.values.map { |e| infer_set(e) })
PHashType.new(unwrap_single_variant(ktype), unwrap_single_variant(etype), size_as_type(o))
end
end
# @api private
def infer_set_Version(o)
PSemVerType.new([SemanticPuppet::VersionRange.new(o, o)])
end
def unwrap_single_variant(possible_variant)
if possible_variant.is_a?(PVariantType) && possible_variant.types.size == 1
possible_variant.types[0]
else
possible_variant
end
end
# Transform int range to a size constraint
# if range == nil the constraint is 1,1
# if range.from == nil min size = 1
# if range.to == nil max size == Infinity
#
def size_range(range)
return [1, 1] if range.nil?
from = range.from
to = range.to
x = from.nil? ? 1 : from
y = to.nil? ? TheInfinity : to
[x, y]
end
# @api private
def self.is_kind_of_callable?(t, optional = true)
t.is_a?(PAnyType) && t.kind_of_callable?(optional)
end
def max(a, b)
a >= b ? a : b
end
def min(a, b)
a <= b ? a : b
end
# Produces the tuple entry at the given index given a tuple type, its from/to constraints on the last
# type, and an index.
# Produces nil if the index is out of bounds
# from must be less than to, and from may not be less than 0
#
# @api private
#
def tuple_entry_at(tuple_t, from, to, index)
regular = (tuple_t.types.size - 1)
if index < regular
tuple_t.types[index]
elsif index < regular + to
# in the varargs part
tuple_t.types[-1]
else
nil
end
end
# Debugging to_s to reduce the amount of output
def to_s
'[a TypeCalculator]'
end
private
def common_rich_data?(t1, t2)
d = TypeFactory.rich_data
d.assignable?(t1) && d.assignable?(t2)
end
def common_data?(t1, t2)
d = TypeFactory.data
d.assignable?(t1) && d.assignable?(t2)
end
def common_scalar_data?(t1, t2)
PScalarDataType::DEFAULT.assignable?(t1) && PScalarDataType::DEFAULT.assignable?(t2)
end
def common_scalar?(t1, t2)
PScalarType::DEFAULT.assignable?(t1) && PScalarType::DEFAULT.assignable?(t2)
end
def common_numeric?(t1, t2)
PNumericType::DEFAULT.assignable?(t1) && PNumericType::DEFAULT.assignable?(t2)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/recursion_guard.rb | lib/puppet/pops/types/recursion_guard.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
# Keeps track of self recursion of conceptual 'this' and 'that' instances using two separate maps and
# a state. The class is used when tracking self recursion in two objects ('this' and 'that') simultaneously.
# A typical example of when this is needed is when testing if 'that' Puppet Type is assignable to 'this'
# Puppet Type since both types may contain self references.
#
# All comparisons are made using the `object_id` of the instance rather than the instance itself.
#
# Hash#compare_by_identity is intentionally not used since we only need to keep
# track of object ids we've seen before, based on object_id, so we don't store
# entire objects in memory.
#
# @api private
class RecursionGuard
attr_reader :state
NO_SELF_RECURSION = 0
SELF_RECURSION_IN_THIS = 1
SELF_RECURSION_IN_THAT = 2
SELF_RECURSION_IN_BOTH = 3
def initialize
@state = NO_SELF_RECURSION
end
# Checks if recursion was detected for the given argument in the 'this' context
# @param instance [Object] the instance to check
# @return [Integer] the resulting state
def recursive_this?(instance)
instance_variable_defined?(:@recursive_this_map) && @recursive_this_map.has_key?(instance.object_id) # rubocop:disable Lint/HashCompareByIdentity
end
# Checks if recursion was detected for the given argument in the 'that' context
# @param instance [Object] the instance to check
# @return [Integer] the resulting state
def recursive_that?(instance)
instance_variable_defined?(:@recursive_that_map) && @recursive_that_map.has_key?(instance.object_id) # rubocop:disable Lint/HashCompareByIdentity
end
# Add the given argument as 'this' invoke the given block with the resulting state
# @param instance [Object] the instance to add
# @return [Object] the result of yielding
def with_this(instance)
if (@state & SELF_RECURSION_IN_THIS) == 0
tc = this_count
@state |= SELF_RECURSION_IN_THIS if this_put(instance)
if tc < this_count
# recursive state detected
result = yield(@state)
# pop state
@state &= ~SELF_RECURSION_IN_THIS
@this_map.delete(instance.object_id)
return result
end
end
yield(@state)
end
# Add the given argument as 'that' invoke the given block with the resulting state
# @param instance [Object] the instance to add
# @return [Object] the result of yielding
def with_that(instance)
if (@state & SELF_RECURSION_IN_THAT) == 0
tc = that_count
@state |= SELF_RECURSION_IN_THAT if that_put(instance)
if tc < that_count
# recursive state detected
result = yield(@state)
# pop state
@state &= ~SELF_RECURSION_IN_THAT
@that_map.delete(instance.object_id)
return result
end
end
yield(@state)
end
# Add the given argument as 'this' and return the resulting state
# @param instance [Object] the instance to add
# @return [Integer] the resulting state
def add_this(instance)
if (@state & SELF_RECURSION_IN_THIS) == 0
@state |= SELF_RECURSION_IN_THIS if this_put(instance)
end
@state
end
# Add the given argument as 'that' and return the resulting state
# @param instance [Object] the instance to add
# @return [Integer] the resulting state
def add_that(instance)
if (@state & SELF_RECURSION_IN_THAT) == 0
@state |= SELF_RECURSION_IN_THAT if that_put(instance)
end
@state
end
# @return the number of objects added to the `this` map
def this_count
instance_variable_defined?(:@this_map) ? @this_map.size : 0
end
# @return the number of objects added to the `that` map
def that_count
instance_variable_defined?(:@that_map) ? @that_map.size : 0
end
private
def this_put(o)
id = o.object_id
@this_map ||= {}
if @this_map.has_key?(id)
@recursive_this_map ||= {}
@recursive_this_map[id] = true
true
else
@this_map[id] = true
false
end
end
def that_put(o)
id = o.object_id
@that_map ||= {}
if @that_map.has_key?(id)
@recursive_that_map ||= {}
@recursive_that_map[id] = true
true
else
@that_map[id] = true
false
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/annotatable.rb | lib/puppet/pops/types/annotatable.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
KEY_ANNOTATIONS = 'annotations'
# Behaviour common to all Pcore annotatable classes
#
# @api public
module Annotatable
TYPE_ANNOTATIONS = PHashType.new(PTypeType.new(PTypeReferenceType.new('Annotation')), PHashType::DEFAULT)
# @return [{PTypeType => PStructType}] the map of annotations
# @api public
def annotations
@annotations.nil? ? EMPTY_HASH : @annotations
end
# @api private
def init_annotatable(init_hash)
@annotations = init_hash[KEY_ANNOTATIONS].freeze
end
# @api private
def annotatable_accept(visitor, guard)
@annotations.each_key { |key| key.accept(visitor, guard) } unless @annotations.nil?
end
# @api private
def _pcore_init_hash
result = {}
result[KEY_ANNOTATIONS] = @annotations unless @annotations.nil?
result
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/implementation_registry.rb | lib/puppet/pops/types/implementation_registry.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
# The {ImplementationRegistry} maps names types in the Puppet Type System to names of corresponding implementation
# modules/classes. Each mapping is unique and bidirectional so that for any given type name there is only one
# implementation and vice versa.
#
# @api private
class ImplementationRegistry
TYPE_REGEXP_SUBST = TypeFactory.tuple([PRegexpType::DEFAULT, PStringType::NON_EMPTY])
# Create a new instance. This method is normally only called once
#
# @param parent [ImplementationRegistry, nil] the parent of this registry
def initialize(parent = nil)
@parent = parent
@type_names_per_implementation = {}
@implementations_per_type_name = {}
@type_name_substitutions = []
@impl_name_substitutions = []
end
# Register a bidirectional type mapping.
#
# @overload register_type_mapping(runtime_type, puppet_type)
# @param runtime_type [PRuntimeType] type that represents the runtime module or class to map to a puppet type
# @param puppet_type [PAnyType] type that will be mapped to the runtime module or class
# @overload register_type_mapping(runtime_type, pattern_replacement)
# @param runtime_type [PRuntimeType] type containing the pattern and replacement to map the runtime type to a puppet type
# @param puppet_type [Array(Regexp,String)] the pattern and replacement to map a puppet type to a runtime type
def register_type_mapping(runtime_type, puppet_type_or_pattern, _ = nil)
TypeAsserter.assert_assignable('First argument of type mapping', PRuntimeType::RUBY, runtime_type)
expr = runtime_type.name_or_pattern
if expr.is_a?(Array)
TypeAsserter.assert_instance_of('Second argument of type mapping', TYPE_REGEXP_SUBST, puppet_type_or_pattern)
register_implementation_regexp(puppet_type_or_pattern, expr)
else
TypeAsserter.assert_instance_of('Second argument of type mapping', PTypeType::DEFAULT, puppet_type_or_pattern)
register_implementation(puppet_type_or_pattern, expr)
end
end
# Register a bidirectional namespace mapping
#
# @param type_namespace [String] the namespace for the puppet types
# @param impl_namespace [String] the namespace for the implementations
def register_implementation_namespace(type_namespace, impl_namespace, _ = nil)
ns = TypeFormatter::NAME_SEGMENT_SEPARATOR
register_implementation_regexp(
[/\A#{type_namespace}#{ns}(\w+)\z/, "#{impl_namespace}#{ns}\\1"],
[/\A#{impl_namespace}#{ns}(\w+)\z/, "#{type_namespace}#{ns}\\1"]
)
end
# Register a bidirectional regexp mapping
#
# @param type_name_subst [Array(Regexp,String)] regexp and replacement mapping type names to runtime names
# @param impl_name_subst [Array(Regexp,String)] regexp and replacement mapping runtime names to type names
def register_implementation_regexp(type_name_subst, impl_name_subst, _ = nil)
@type_name_substitutions << type_name_subst
@impl_name_substitutions << impl_name_subst
nil
end
# Register a bidirectional mapping between a type and an implementation
#
# @param type [PAnyType,String] the type or type name
# @param impl_module[Module,String] the module or module name
def register_implementation(type, impl_module, _ = nil)
type = type.name if type.is_a?(PAnyType)
impl_module = impl_module.name if impl_module.is_a?(Module)
@type_names_per_implementation[impl_module] = type
@implementations_per_type_name[type] = impl_module
nil
end
# Find the name for the module that corresponds to the given type or type name
#
# @param type [PAnyType,String] the name of the type
# @return [String,nil] the name of the implementation module, or `nil` if no mapping was found
def module_name_for_type(type)
type = type.name if type.is_a?(PAnyType)
name = @parent.module_name_for_type(type) unless @parent.nil?
name.nil? ? find_mapping(type, @implementations_per_type_name, @type_name_substitutions) : name
end
# Find the module that corresponds to the given type or type name
#
# @param type [PAnyType,String] the name of the type
# @return [Module,nil] the name of the implementation module, or `nil` if no mapping was found
def module_for_type(type)
name = module_name_for_type(type)
# TODO Shouldn't ClassLoader be module specific?
name.nil? ? nil : ClassLoader.provide(name)
end
# Find the type name and loader that corresponds to the given runtime module or module name
#
# @param impl_module [Module,String] the implementation class or class name
# @return [String,nil] the name of the type, or `nil` if no mapping was found
def type_name_for_module(impl_module)
impl_module = impl_module.name if impl_module.is_a?(Module)
name = @parent.type_name_for_module(impl_module) unless @parent.nil?
name.nil? ? find_mapping(impl_module, @type_names_per_implementation, @impl_name_substitutions) : name
end
# Find the name for, and then load, the type that corresponds to the given runtime module or module name
# The method will return `nil` if no mapping is found, a TypeReference if a mapping was found but the
# loader didn't find the type, or the loaded type.
#
# @param impl_module [Module,String] the implementation class or class name
# @return [PAnyType,nil] the type, or `nil` if no mapping was found
def type_for_module(impl_module)
name = type_name_for_module(impl_module)
if name.nil?
nil
else
TypeParser.singleton.parse(name)
end
end
private
def find_mapping(name, names, substitutions)
found = names[name]
if found.nil?
substitutions.each do |subst|
substituted = name.sub(*subst)
return substituted unless substituted == name
end
end
found
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/types/p_timestamp_type.rb | lib/puppet/pops/types/p_timestamp_type.rb | # frozen_string_literal: true
module Puppet::Pops
module Types
class PTimestampType < PAbstractTimeDataType
def self.register_ptype(loader, ir)
create_ptype(loader, ir, 'ScalarType',
'from' => { KEY_TYPE => POptionalType.new(PTimestampType::DEFAULT), KEY_VALUE => nil },
'to' => { KEY_TYPE => POptionalType.new(PTimestampType::DEFAULT), KEY_VALUE => nil })
end
def self.new_function(type)
@new_function ||= Puppet::Functions.create_loaded_function(:new_timestamp, type.loader) do
local_types do
type 'Formats = Variant[String[2],Array[String[2], 1]]'
end
dispatch :now do
end
dispatch :from_seconds do
param 'Variant[Integer,Float]', :seconds
end
dispatch :from_string do
param 'String[1]', :string
optional_param 'Formats', :format
optional_param 'String[1]', :timezone
end
dispatch :from_string_hash do
param <<-TYPE, :hash_arg
Struct[{
string => String[1],
Optional[format] => Formats,
Optional[timezone] => String[1]
}]
TYPE
end
def now
Time::Timestamp.now
end
def from_string(string, format = :default, timezone = nil)
Time::Timestamp.parse(string, format, timezone)
end
def from_string_hash(args_hash)
Time::Timestamp.from_hash(args_hash)
end
def from_seconds(seconds)
Time::Timestamp.new((seconds * Time::NSECS_PER_SEC).to_i)
end
end
end
def generalize
DEFAULT
end
def impl_class
Time::Timestamp
end
def instance?(o, guard = nil)
o.is_a?(Time::Timestamp) && o >= @from && o <= @to
end
DEFAULT = PTimestampType.new(nil, nil)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/migration/migration_checker.rb | lib/puppet/pops/migration/migration_checker.rb | # frozen_string_literal: true
# This class defines the private API of the MigrationChecker support.
# @api private
#
class Puppet::Pops::Migration::MigrationChecker
def initialize
end
# rubocop:disable Naming/MemoizedInstanceVariableName
def self.singleton
@null_checker ||= new
end
# rubocop:enable Naming/MemoizedInstanceVariableName
# Produces a hash of available migrations; a map from a symbolic name in string form to a brief description.
# This version has no such supported migrations.
def available_migrations
{}
end
# For 3.8/4.0
def report_ambiguous_integer(o)
raise Puppet::DevError, _("Unsupported migration method called")
end
# For 3.8/4.0
def report_ambiguous_float(o)
raise Puppet::DevError, _("Unsupported migration method called")
end
# For 3.8/4.0
def report_empty_string_true(value, o)
raise Puppet::DevError, _("Unsupported migration method called")
end
# For 3.8/4.0
def report_uc_bareword_type(value, o)
raise Puppet::DevError, _("Unsupported migration method called")
end
# For 3.8/4.0
def report_equality_type_mismatch(left, right, o)
raise Puppet::DevError, _("Unsupported migration method called")
end
# For 3.8/4.0
def report_option_type_mismatch(test_value, option_value, option_expr, matching_expr)
raise Puppet::DevError, _("Unsupported migration method called")
end
# For 3.8/4.0
def report_in_expression(o)
raise Puppet::DevError, _("Unsupported migration method called")
end
# For 3.8/4.0
def report_array_last_in_block(o)
raise Puppet::DevError, _("Unsupported migration method called")
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/functions/dispatch.rb | lib/puppet/pops/functions/dispatch.rb | # frozen_string_literal: true
module Puppet::Pops
module Functions
# Defines a connection between a implementation method and the signature that
# the method will handle.
#
# This interface should not be used directly. Instead dispatches should be
# constructed using the DSL defined in {Puppet::Functions}.
#
# @api private
class Dispatch < Evaluator::CallableSignature
# @api public
attr_reader :type
# TODO: refactor to parameter_names since that makes it API
attr_reader :param_names
attr_reader :injections
# Describes how arguments are woven if there are injections, a regular argument is a given arg index, an array
# an injection description.
#
attr_reader :weaving
# @api public
attr_reader :block_name
# @param type [Puppet::Pops::Types::PArrayType, Puppet::Pops::Types::PTupleType] - type describing signature
# @param method_name [String] the name of the method that will be called when type matches given arguments
# @param param_names [Array<String>] names matching the number of parameters specified by type (or empty array)
# @param block_name [String,nil] name of block parameter, no nil
# @param injections [Array<Array>] injection data for weaved parameters
# @param weaving [Array<Integer,Array>] weaving knits
# @param last_captures [Boolean] true if last parameter is captures rest
# @param argument_mismatch_handler [Boolean] true if this is a dispatch for an argument mismatch
# @api private
def initialize(type, method_name, param_names, last_captures = false, block_name = nil, injections = EMPTY_ARRAY, weaving = EMPTY_ARRAY, argument_mismatch_handler = false)
@type = type
@method_name = method_name
@param_names = param_names
@last_captures = last_captures
@block_name = block_name
@injections = injections
@weaving = weaving
@argument_mismatch_handler = argument_mismatch_handler
end
# @api private
def parameter_names
@param_names
end
# @api private
def last_captures_rest?
@last_captures
end
def argument_mismatch_handler?
@argument_mismatch_handler
end
# @api private
def invoke(instance, calling_scope, args, &block)
result = instance.send(@method_name, *weave(calling_scope, args), &block)
return_type = @type.return_type
Types::TypeAsserter.assert_instance_of(nil, return_type, result) { "value returned from function '#{@method_name}'" } unless return_type.nil?
result
end
# @api private
def weave(scope, args)
# no need to weave if there are no injections
if @injections.empty?
args
else
new_args = []
@weaving.each do |knit|
if knit.is_a?(Array)
injection_name = @injections[knit[0]]
new_args <<
case injection_name
when :scope
scope
when :pal_script_compiler
Puppet.lookup(:pal_script_compiler)
when :cache
Puppet::Pops::Adapters::ObjectIdCacheAdapter.adapt(scope.compiler)
when :pal_catalog_compiler
Puppet.lookup(:pal_catalog_compiler)
when :pal_compiler
Puppet.lookup(:pal_compiler)
else
raise ArgumentError, _("Unknown injection %{injection_name}") % { injection_name: injection_name }
end
elsif knit < 0
# Careful so no new nil arguments are added since they would override default
# parameter values in the received
idx = -knit - 1
new_args += args[idx..] if idx < args.size
elsif knit < args.size
new_args << args[knit]
end
end
new_args
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/functions/dispatcher.rb | lib/puppet/pops/functions/dispatcher.rb | # frozen_string_literal: true
# Evaluate the dispatches defined as {Puppet::Pops::Functions::Dispatch}
# instances to call the appropriate method on the
# {Puppet::Pops::Functions::Function} instance.
#
# @api private
class Puppet::Pops::Functions::Dispatcher
attr_reader :dispatchers
# @api private
def initialize
@dispatchers = []
end
# Answers if dispatching has been defined
# @return [Boolean] true if dispatching has been defined
#
# @api private
def empty?
@dispatchers.empty?
end
def find_matching_dispatcher(args, &block)
@dispatchers.find { |d| d.type.callable_with?(args, block) }
end
# Dispatches the call to the first found signature (entry with matching type).
#
# @param instance [Puppet::Functions::Function] - the function to call
# @param calling_scope [T.B.D::Scope] - the scope of the caller
# @param args [Array<Object>] - the given arguments in the form of an Array
# @return [Object] - what the called function produced
#
# @api private
def dispatch(instance, calling_scope, args, &block)
dispatcher = find_matching_dispatcher(args, &block)
unless dispatcher
args_type = Puppet::Pops::Types::TypeCalculator.singleton.infer_set(block_given? ? args + [block] : args)
raise ArgumentError, Puppet::Pops::Types::TypeMismatchDescriber.describe_signatures(instance.class.name, signatures, args_type)
end
if dispatcher.argument_mismatch_handler?
msg = dispatcher.invoke(instance, calling_scope, args)
raise ArgumentError, "'#{instance.class.name}' #{msg}"
end
catch(:next) do
dispatcher.invoke(instance, calling_scope, args, &block)
end
end
# Adds a dispatch directly to the set of dispatchers.
# @api private
def add(a_dispatch)
@dispatchers << a_dispatch
end
# Produces a CallableType for a single signature, and a Variant[<callables>] otherwise
#
# @api private
def to_type
# make a copy to make sure it can be contained by someone else (even if it is not contained here, it
# should be treated as immutable).
#
callables = dispatchers.map(&:type)
# multiple signatures, produce a Variant type of Callable1-n (must copy them)
# single signature, produce single Callable
callables.size > 1 ? Puppet::Pops::Types::TypeFactory.variant(*callables) : callables.pop
end
# @api private
def signatures
@dispatchers.reject(&:argument_mismatch_handler?)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/functions/function.rb | lib/puppet/pops/functions/function.rb | # frozen_string_literal: true
# @note WARNING: This new function API is still under development and may change at
# any time
#
# A function in the puppet evaluator.
#
# Functions are normally defined by another system, which produces subclasses
# of this class as well as constructing delegations to call the appropriate methods.
#
# This class should rarely be used directly. Instead functions should be
# constructed using {Puppet::Functions.create_function}.
#
# @api public
class Puppet::Pops::Functions::Function
# The loader that loaded this function.
# Should be used if function wants to load other things.
#
attr_reader :loader
def initialize(closure_scope, loader)
@closure_scope = closure_scope
@loader = loader
end
# Invokes the function via the dispatching logic that performs type check and weaving.
# A specialized function may override this method to do its own dispatching and checking of
# the raw arguments. A specialized implementation can rearrange arguments, add or remove
# arguments and then delegate to the dispatching logic by calling:
#
# @example Delegating to the dispatcher
# def call(scope, *args)
# manipulated_args = args + ['easter_egg']
# self.class.dispatcher.dispatch(self, scope, manipulated_args)
# end
#
# System functions that must have access to the calling scope can use this technique. Functions
# in general should not need the calling scope. (The closure scope; what is visible where the function
# is defined) is available via the method `closure_scope`).
#
# @api public
def call(scope, *args, &block)
result = catch(:return) do
return self.class.dispatcher.dispatch(self, scope, args, &block)
end
result.value
rescue Puppet::Pops::Evaluator::Next => jumper
begin
throw :next, jumper.value
rescue Puppet::Parser::Scope::UNCAUGHT_THROW_EXCEPTION
raise Puppet::ParseError.new("next() from context where this is illegal", jumper.file, jumper.line)
end
rescue Puppet::Pops::Evaluator::Return => jumper
begin
throw :return, jumper
rescue Puppet::Parser::Scope::UNCAUGHT_THROW_EXCEPTION
raise Puppet::ParseError.new("return() from context where this is illegal", jumper.file, jumper.line)
end
end
# Allows the implementation of a function to call other functions by name. The callable functions
# are those visible to the same loader that loaded this function (the calling function). The
# referenced function is called with the calling functions closure scope as the caller's scope.
#
# @param function_name [String] The name of the function
# @param *args [Object] splat of arguments
# @return [Object] The result returned by the called function
#
# @api public
def call_function(function_name, *args, &block)
internal_call_function(closure_scope, function_name, args, &block)
end
# The scope where the function was defined
def closure_scope
# If closure scope is explicitly set to not nil, if there is a global scope, otherwise an empty hash
@closure_scope || Puppet.lookup(:global_scope) { {} }
end
# The dispatcher for the function
#
# @api private
def self.dispatcher
@dispatcher ||= Puppet::Pops::Functions::Dispatcher.new
end
# Produces information about parameters in a way that is compatible with Closure
#
# @api private
def self.signatures
@dispatcher.signatures
end
protected
# Allows the implementation of a function to call other functions by name and pass the caller
# scope. The callable functions are those visible to the same loader that loaded this function
# (the calling function).
#
# @param scope [Puppet::Parser::Scope] The caller scope
# @param function_name [String] The name of the function
# @param args [Array] array of arguments
# @return [Object] The result returned by the called function
#
# @api public
def internal_call_function(scope, function_name, args, &block)
the_loader = loader
unless the_loader
raise ArgumentError, _("Function %{class_name}(): cannot call function '%{function_name}' - no loader specified") %
{ class_name: self.class.name, function_name: function_name }
end
func = the_loader.load(:function, function_name)
if func
Puppet::Util::Profiler.profile(function_name, [:functions, function_name]) do
return func.call(scope, *args, &block)
end
end
# Check if a 3x function is present. Raise a generic error if it's not to allow upper layers to fill in the details
# about where in a puppet manifest this error originates. (Such information is not available here).
loader_scope = closure_scope
func_3x = Puppet::Parser::Functions.function(function_name, loader_scope.environment) if loader_scope.is_a?(Puppet::Parser::Scope)
unless func_3x
raise ArgumentError, _("Function %{class_name}(): Unknown function: '%{function_name}'") %
{ class_name: self.class.name, function_name: function_name }
end
# Call via 3x API
# Arguments must be mapped since functions are unaware of the new and magical creatures in 4x.
# NOTE: Passing an empty string last converts nil/:undef to empty string
result = scope.send(func_3x, Puppet::Pops::Evaluator::Runtime3FunctionArgumentConverter.map_args(args, loader_scope, ''), &block)
# Prevent non r-value functions from leaking their result (they are not written to care about this)
Puppet::Parser::Functions.rvalue?(function_name) ? result : nil
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/parser/parser_support.rb | lib/puppet/pops/parser/parser_support.rb | # frozen_string_literal: true
require_relative '../../../puppet/parser/functions'
require_relative '../../../puppet/parser/files'
require_relative '../../../puppet/resource/type_collection'
require_relative '../../../puppet/resource/type'
require 'monitor'
module Puppet::Pops
module Parser
# Supporting logic for the parser.
# This supporting logic has slightly different responsibilities compared to the original Puppet::Parser::Parser.
# It is only concerned with parsing.
#
class Parser
# Note that the name of the contained class and the file name (currently parser_support.rb)
# needs to be different as the class is generated by Racc, and this file (parser_support.rb) is included as a mix in
#
# Simplify access to the Model factory
# Note that the parser/parser support does not have direct knowledge about the Model.
# All model construction/manipulation is made by the Factory.
#
Factory = Model::Factory
attr_accessor :lexer
attr_reader :definitions
# Returns the token text of the given lexer token, or nil, if token is nil
def token_text t
return t if t.nil?
if t.is_a?(Factory) && t.model_class <= Model::QualifiedName
t['value']
elsif t.is_a?(Model::QualifiedName)
t.value
else
# else it is a lexer token
t[:value]
end
end
# Produces the fully qualified name, with the full (current) namespace for a given name.
#
# This is needed because class bodies are lazily evaluated and an inner class' container(s) may not
# have been evaluated before some external reference is made to the inner class; its must therefore know its complete name
# before evaluation-time.
#
def classname(name)
[namespace, name].join('::').sub(/^::/, '')
end
# Raises a Parse error with location information. Information about file is always obtained from the
# lexer. Line and position is produced if the given semantic is a Positioned object and have been given an offset.
#
def error(semantic, message)
except = Puppet::ParseError.new(message)
if semantic.is_a?(LexerSupport::TokenValue)
except.file = semantic[:file];
except.line = semantic[:line];
except.pos = semantic[:pos];
else
locator = @lexer.locator
except.file = locator.file
if semantic.is_a?(Factory)
offset = semantic['offset']
unless offset.nil?
except.line = locator.line_for_offset(offset)
except.pos = locator.pos_on_line(offset)
end
end
end
raise except
end
# Parses a file expected to contain pp DSL logic.
def parse_file(file)
unless Puppet::FileSystem.exist?(file)
unless file =~ /\.pp$/
file += ".pp"
end
end
@lexer.file = file
_parse
end
def initialize
@lexer = Lexer2.new
@namestack = []
@definitions = []
end
# This is a callback from the generated parser (when an error occurs while parsing)
#
def on_error(token, value, stack)
if token == 0 # denotes end of file
value_at = 'end of input'
else
value_at = "'#{value[:value]}'"
end
error = Issues::SYNTAX_ERROR.format(:where => value_at)
error = "#{error}, token: #{token}" if @yydebug
# Note, old parser had processing of "expected token here" - do not try to reinstate:
# The 'expected' is only of value at end of input, otherwise any parse error involving a
# start of a pair will be reported as expecting the close of the pair - e.g. "$x.each |$x {|", would
# report that "seeing the '{', the '}' is expected. That would be wrong.
# Real "expected" tokens are very difficult to compute (would require parsing of racc output data). Output of the stack
# could help, but can require extensive backtracking and produce many options.
#
# The lexer should handle the "expected instead of end of file for strings, and interpolation", other expectancies
# must be handled by the grammar. The lexer may have enqueued tokens far ahead - the lexer's opinion about this
# is not trustworthy.
#
file = nil
line = nil
pos = nil
if token != 0
file = value[:file]
locator = value.locator
if locator.is_a?(Puppet::Pops::Parser::Locator::SubLocator)
# The error occurs when doing sub-parsing and the token must be transformed
# Transpose the local offset, length to global "coordinates"
global_offset, _ = locator.to_global(value.offset, value.length)
line = locator.locator.line_for_offset(global_offset)
pos = locator.locator.pos_on_line(global_offset)
else
line = value[:line]
pos = value[:pos]
end
else
# At end of input, use what the lexer thinks is the source file
file = lexer.file
end
file = nil unless file.is_a?(String) && !file.empty?
raise Puppet::ParseErrorWithIssue.new(error, file, line, pos, nil, Issues::SYNTAX_ERROR.issue_code)
end
# Parses a String of pp DSL code.
#
def parse_string(code, path = nil)
@lexer.lex_string(code, path)
_parse()
end
# Mark the factory wrapped model object with location information
# @return [Factory] the given factory
# @api private
#
def loc(factory, start_locatable, end_locatable = nil)
factory.record_position(@lexer.locator, start_locatable, end_locatable)
end
# Mark the factory wrapped heredoc model object with location information
# @return [Factory] the given factory
# @api private
#
def heredoc_loc(factory, start_locatable, end_locatable = nil)
factory.record_heredoc_position(start_locatable, end_locatable)
end
def aryfy(o)
o = [o] unless o.is_a?(Array)
o
end
def namespace
@namestack.join('::')
end
def namestack(name)
@namestack << name
end
def namepop
@namestack.pop
end
def add_definition(definition)
@definitions << definition.model
definition
end
# Transforms an array of expressions containing literal name expressions to calls if followed by an
# expression, or expression list
#
def transform_calls(expressions)
# Factory transform raises an error if a non qualified name is followed by an argument list
# since there is no way that that can be transformed back to sanity. This occurs in situations like this:
#
# $a = 10, notice hello
#
# where the "10, notice" forms an argument list. The parser builds an Array with the expressions and includes
# the comma tokens to enable the error to be reported against the first comma.
#
Factory.transform_calls(expressions)
rescue Factory::ArgsToNonCallError => e
# e.args[1] is the first comma token in the list
# e.name_expr is the function name expression
if e.name_expr.is_a?(Factory) && e.name_expr.model_class <= Model::QualifiedName
error(e.args[1], _("attempt to pass argument list to the function '%{name}' which cannot be called without parentheses") % { name: e.name_expr['value'] })
else
error(e.args[1], _("illegal comma separated argument list"))
end
end
# Transforms a LEFT followed by the result of attribute_operations, this may be a call or an invalid sequence
def transform_resource_wo_title(left, resource, lbrace_token, rbrace_token)
Factory.transform_resource_wo_title(left, resource, lbrace_token, rbrace_token)
end
# Creates a program with the given body.
#
def create_program(body)
locator = @lexer.locator
Factory.PROGRAM(body, definitions, locator)
end
# Creates an empty program with a single No-op at the input's EOF offset with 0 length.
#
def create_empty_program
locator = @lexer.locator
no_op = Factory.literal(nil)
# Create a synthetic NOOP token at EOF offset with 0 size. The lexer does not produce an EOF token that is
# visible to the grammar rules. Creating this token is mainly to reuse the positioning logic as it
# expects a token decorated with location information.
_, token = @lexer.emit_completed([:NOOP, '', 0], locator.string.bytesize)
loc(no_op, token)
# Program with a Noop
Factory.PROGRAM(no_op, [], locator)
end
# Performs the parsing and returns the resulting model.
# The lexer holds state, and this is setup with {#parse_string}, or {#parse_file}.
#
# @api private
#
def _parse
begin
@yydebug = false
main = yyparse(@lexer, :scan)
end
main
ensure
@lexer.clear
@namestack = []
@definitions = []
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/parser/eparser.rb | lib/puppet/pops/parser/eparser.rb | #
# DO NOT MODIFY!!!!
# This file is automatically generated by Racc 1.5.2
# from Racc grammar file "".
#
require 'racc/parser.rb'
require_relative '../../../puppet'
require_relative '../../../puppet/pops'
module Puppet
class ParseError < Puppet::Error; end
class ImportError < Racc::ParseError; end
class AlreadyImportedError < ImportError; end
end
module Puppet
module Pops
module Parser
class Parser < Racc::Parser
module_eval(<<'...end egrammar.ra/module_eval...', 'egrammar.ra', 885)
# Make emacs happy
# Local Variables:
# mode: ruby
# End:
...end egrammar.ra/module_eval...
##### State transition tables begin ###
clist = [
'69,72,283,-267,70,64,79,65,83,84,85,64,110,65,-276,376,304,163,396,305',
'65,-145,326,284,20,19,112,-281,115,-279,377,51,111,54,82,60,12,250,57',
'43,46,271,53,44,10,11,-267,90,77,18,164,147,45,114,77,16,17,-276,86',
'88,87,89,125,78,-145,327,122,141,148,52,-281,272,-279,42,73,91,75,76',
'74,251,155,58,48,61,62,55,56,69,72,63,144,70,64,283,65,63,444,125,124',
'110,166,122,121,283,118,445,77,440,182,439,123,20,19,112,284,115,77',
'125,51,111,54,122,60,12,284,57,43,46,80,53,44,10,11,124,184,77,18,121',
'276,45,114,428,16,17,125,123,427,125,122,187,78,122,82,124,125,252,52',
'121,122,141,42,73,91,75,76,123,263,262,58,48,61,62,55,56,69,72,63,90',
'70,64,124,65,144,124,121,125,489,121,141,122,124,427,123,90,121,123',
'125,264,20,19,122,440,123,439,265,51,-225,54,266,60,12,144,57,43,46',
'147,53,44,10,11,269,124,77,18,270,121,45,263,262,16,17,125,124,123,125',
'122,121,78,122,263,262,125,274,52,123,122,295,42,73,296,75,76,263,262',
'302,58,48,61,62,55,56,69,72,63,-226,70,64,124,65,302,124,121,69,72,121',
'82,70,124,90,123,90,121,123,90,423,20,19,307,306,123,318,319,51,90,54',
'324,60,12,110,57,43,46,155,53,44,10,11,332,350,77,18,351,112,45,115',
'353,16,17,111,69,72,357,363,70,78,367,369,77,372,373,52,283,386,387',
'42,73,266,75,76,114,391,274,58,48,61,62,55,56,69,72,63,397,70,64,110',
'65,399,372,-225,163,404,406,160,413,414,324,325,417,112,420,115,372',
'20,19,111,372,147,429,430,51,433,54,78,60,127,110,57,43,46,434,53,44',
'164,73,437,114,77,18,441,112,45,115,443,16,17,111,69,72,452,453,70,78',
'455,457,324,461,463,52,324,466,467,42,73,469,75,76,114,473,443,58,48',
'61,62,55,56,69,72,63,475,70,64,110,65,477,478,479,163,480,332,160,485',
'283,486,487,488,112,499,115,500,20,19,111,501,503,77,504,51,505,54,78',
'60,127,284,57,43,46,506,53,44,164,73,353,114,77,18,,316,45,,,16,17,',
'69,72,,,70,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63',
',70,64,,65,,,,163,,,160,,,,,,,,,,20,19,,,358,,,51,360,54,78,60,127,283',
'57,43,46,283,53,44,164,73,,,77,18,77,,45,,77,16,17,,284,,,,284,78,,',
',,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,',
',,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,',
',45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69',
'72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46',
',53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,',
',,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,136,,',
',,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,69,72,',
',70,78,,,,,,52,,,,42,73,,75,76,,,,138,137,61,62,55,56,69,72,63,,70,64',
',65,,,,163,,,160,,,,,,,,,,20,19,,,,,,51,,54,78,60,127,,57,43,46,,53',
'44,164,73,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58',
'48,61,62,55,56,69,72,63,110,70,64,,65,,,,,,,,,,112,,115,,,,111,20,19',
',,,,,51,,54,,60,127,,57,43,46,,53,44,114,,,,77,18,,,45,,,16,17,,,92',
'93,,,78,,,91,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,110',
'70,64,,65,,,,,,,,,,112,,115,,,,111,20,19,,,,,,51,,54,,60,127,,57,43',
'46,,53,44,114,,,,77,18,,,45,,,16,17,,,92,93,,,78,,,91,,,52,,,,42,73',
',75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,168,65,,,,,,,,,,,,,,,,,20',
'19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,',
',,,,78,,,,,,52,,,,42,73,,75,76,,,,138,137,61,62,55,56,69,72,63,,70,64',
'173,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10',
'11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,138,137',
'61,62,55,56,69,72,63,,70,64,,65,175,,,,,,,,,,,,,,,,20,19,,,,,,51,,54',
',60,12,,57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52',
',,,42,73,,75,76,,,,138,137,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,',
',,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45',
',,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72',
'63,110,70,64,,186,,,,,,,,,,112,,115,,,,111,20,19,,,,,,51,,54,,60,127',
',57,43,46,,53,44,114,,,,77,18,,,45,,,16,17,,,92,93,,,78,,,91,,,52,,',
',42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,',
',,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45,,,16',
'17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70',
'64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10',
'11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61',
'62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12',
',57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73',
',75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19',
',,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,',
',78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65',
',,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77',
'18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56',
'69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43',
'46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76',
',,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,',
'51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,',
',,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,',
',,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18',
',,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69',
'72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46',
',53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,',
',,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,204',
'219,210,220,60,213,222,214,43,202,,206,200,,,,,77,18,223,218,201,,,16',
'199,,,,,,,78,,,,,221,205,,,,42,73,,75,76,,,,215,203,216,217,211,212',
'69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43',
'46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,',
',58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51',
',54,,60,127,,57,43,46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52',
',,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,',
',,,,,20,19,,,,,,51,,54,,60,127,,57,43,46,,53,44,,,,,77,18,,,45,,,16',
'17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70',
'64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43,46,,53,44,,',
',,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62',
'55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127',
',57,43,46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75',
'76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,',
',,,51,,54,,60,127,,57,43,46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,',
',,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,',
',,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43,46,,53,44,,,,,77,18,,,45',
',,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72',
'63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43,46,,53',
'44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48',
'61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60',
'127,,57,43,46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73',
',75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19',
',,,,,51,,54,,60,127,,57,43,46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78',
',,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,',
',,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43,46,,53,44,,,,,77,18,,',
'45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69',
'72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43,46',
',53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58',
'48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54',
',60,127,,57,43,46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,',
'42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,',
',,20,19,,,,,,51,,54,,60,127,,57,43,46,,53,44,,,,,77,18,,,45,,,16,17',
',,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64',
',65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43,46,,53,44,,,,,77',
'18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56',
'69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43',
'46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,',
',58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51',
',54,,60,127,,57,43,46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52',
',,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,',
',,,,,20,19,,,,,,51,,54,,60,127,,57,43,46,,53,44,,,,,77,18,,,45,,,16',
'17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70',
'64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43,46,,53,44,,',
',,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,245,42,73,,75,76,,,,58,48,61',
'62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12',
',57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73',
',75,76,,,,138,137,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20',
'19,,,,,,51,,54,,60,127,,57,43,46,,53,44,,,,,77,18,,,45,,,16,17,,,,,',
',78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65',
',,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43,46,,53,44,,,,,77,18',
',,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69',
'72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43,46',
',53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58',
'48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,287,,,,,51',
',54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,',
',52,,,,42,73,,75,76,,,,138,137,61,62,55,56,69,72,63,,70,64,,65,,,,,',
',,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,',
',45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,138,137,61,62,55,56',
'69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43',
'46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76',
',,,58,48,61,62,55,56,69,72,63,,70,64,,65,175,,,,,,,,,,,,,,,,20,19,,',
',,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78',
',,,,,52,,,,42,73,,75,76,,,,138,137,61,62,55,56,69,72,63,,70,64,,65,',
',325,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43,46,,53,44,,,,,77',
'18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56',
'69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43',
'46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,',
',58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51',
',54,,60,127,,57,43,46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52',
',,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,',
',,,,,20,19,,,,,,51,,54,,60,127,,57,43,46,,53,44,,,,,77,18,,,45,,,16',
'17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70',
'64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43,46,,53,44,,',
',,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62',
'55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,',
'57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73',
',75,76,,,,138,137,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20',
'19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,',
',,,,78,,,,,,52,,,,42,73,,75,76,,,,138,137,61,62,55,56,69,72,63,,70,64',
',65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11',
',,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,138,137,61',
'62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12',
',57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73',
',75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,379,,,,,,,,,,,,,,,,20',
'19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,',
',,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64',
',65,381,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10',
'11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61',
'62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127',
',57,43,46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75',
'76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,',
',,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78',
',,,,,52,,,,42,73,,75,76,,,,138,137,61,62,55,56,69,72,63,,70,64,,65,400',
',,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77',
'18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,138,137,61,62,55',
'56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57',
'43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75',
'76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,',
',,,51,,54,,60,127,,57,43,46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,',
',,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,',
',,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43,46,,53,44,,,,,77,18,,,45',
',,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72',
'63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43,46,,53',
'44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48',
'61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60',
'127,,57,43,46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73',
',75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19',
',,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,',
',78,,,,,,52,,,,42,73,,75,76,,,,138,137,61,62,55,56,69,72,63,,70,64,',
'65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43,46,,53,44,,,,,77',
'18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56',
'69,72,63,,70,64,,65,432,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57',
'43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75',
'76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,',
',,,51,,54,,60,127,,57,43,46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,',
',,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,',
',,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18',
',,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,138,137,61,62,55,56',
'69,72,63,,70,64,,65,446,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57',
'43,46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76',
',,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,',
'51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,',
',,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,',
',,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18',
',,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69',
'72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46',
',53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,',
',,138,137,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,',
',51,,54,,60,127,,57,43,46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,',
',,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,',
',,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,',
'45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69',
'72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46',
',53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,',
',,138,137,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,',
',51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78',
',,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,',
',,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18',
',,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,138,137,61,62,55,56',
'69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43',
'46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,',
',58,48,61,62,55,56,69,72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51',
',54,,60,127,,57,43,46,,53,44,,,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52',
',,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,482,,,,,,,',
',,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45',
',,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72',
'63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53',
'44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58',
'48,61,62,55,56,69,72,63,,70,64,,65,491,,,,,,,,,,,,,,,,20,19,,,,,,51',
',54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,',
',52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,493,,,',
',,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18',
',,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69',
'72,63,,70,64,,65,,,,,,,,,,,,,,,,,20,19,,,,,,51,,54,,60,12,,57,43,46',
',53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,',
',,58,48,61,62,55,56,69,72,63,,70,64,,65,498,,,,,,,,,,,,,,,,20,19,,,',
',,51,,54,,60,12,,57,43,46,,53,44,10,11,,,77,18,,,45,,,16,17,,,,,,,78',
',,,,,52,,,,42,73,,75,76,,,,58,48,61,62,55,56,69,72,63,,70,64,,65,,,',
',,,,,,,,,,,,,20,19,,,,,,51,,54,,60,127,,57,43,46,,53,44,,,,,77,18,,',
'45,,,16,17,,,,,,,78,,,,,,52,,,,42,73,,75,76,110,,,58,48,61,62,55,56',
',,63,106,101,112,,115,,109,,111,,102,104,103,105,,,,,,,,,,,,,,,,114',
',,,108,107,,,94,95,97,96,99,100,,92,93,110,,288,,,91,,,,,,,106,101,112',
',115,,109,,111,,102,104,103,105,,,98,,,,,,,,,,,,,114,,,,108,107,,,94',
'95,97,96,99,100,,92,93,110,,289,,,91,,,,,,,106,101,112,,115,,109,,111',
',102,104,103,105,,,98,,,,,,,,,,,,,114,,,,108,107,,,94,95,97,96,99,100',
',92,93,110,,290,,,91,,,,,,,106,101,112,,115,,109,,111,,102,104,103,105',
',,98,,,,,,,,,,,,,114,,,,108,107,,110,94,95,97,96,99,100,,92,93,,,106',
'101,112,91,115,,109,,111,,102,104,103,105,,,,,,,,,,,,,98,,,114,,,,108',
'107,,,94,95,97,96,99,100,,92,93,,,,,,91,,110,,,,,,,,,318,319,,106,101',
'112,322,115,110,109,,111,98,102,104,103,105,,,,,,112,,115,,,,111,,,',
'114,,,,108,107,,,94,95,97,96,99,100,,92,93,114,,,110,,91,,,,,97,96,',
',,92,93,112,,115,110,,91,111,,,,,98,,,,,,112,,115,,,,111,,,,114,98,',
',,,,,,,97,96,,,,92,93,114,,,110,,91,,,94,95,97,96,,,,92,93,112,,115',
'110,,91,111,,,,,98,,,,,,112,,115,,,,111,,,,114,98,,,,,,,94,95,97,96',
',,,92,93,114,,,110,,91,,,94,95,97,96,99,100,,92,93,112,,115,110,,91',
'111,,,,,98,,,,,101,112,,115,,,,111,,102,,114,98,,,,,,,94,95,97,96,99',
'100,,92,93,114,,,,,91,,110,94,95,97,96,99,100,,92,93,,,,101,112,91,115',
'110,,,111,98,102,,,,,,,,101,112,,115,,,,111,98,102,,114,,,,,,,,94,95',
'97,96,99,100,,92,93,114,,,,,91,,110,94,95,97,96,99,100,,92,93,,,,101',
'112,91,115,,,,111,98,102,,,,,,,,,,,,,,,,98,,,114,,,,,110,,,94,95,97',
'96,99,100,,92,93,106,101,112,,115,91,109,,111,,102,104,103,105,,,,,',
',,,,,,,,,98,114,,,,,110,,,94,95,97,96,99,100,,92,93,106,101,112,,115',
'91,109,,111,,102,104,103,105,,,,,,,,,,,,,,,98,114,,,,,107,,,94,95,97',
'96,99,100,110,92,93,,,328,,,91,,,,106,101,112,,115,,109,,111,,102,104',
'103,105,,,,,,98,,,,,,,,,,114,,,,108,107,,,94,95,97,96,99,100,,92,93',
'110,-65,,,,91,-65,,,,,,106,101,112,,115,,109,,111,,102,104,103,105,',
',98,,,,,,,,,,,,,114,,,,108,107,,110,94,95,97,96,99,100,,92,93,,,106',
'101,112,91,115,,109,,111,,102,104,103,105,,,,,,,,,,,,,98,,,114,,,,108',
'107,,,94,95,97,96,99,100,110,92,93,,,,,,91,,,,106,101,112,354,115,,109',
',111,,102,104,103,105,,,,,,98,,,,,,,,,,114,,,,108,107,,110,94,95,97',
'96,99,100,,92,93,,,106,101,112,91,115,,109,,111,,102,104,103,105,,,',
',,,,,,,,,98,,,114,,,,108,107,,110,94,95,97,96,99,100,,92,93,,,106,101',
'112,91,115,,109,,111,,102,104,103,105,,,,,,,,,,,,,98,,,114,,,,108,107',
',110,94,95,97,96,99,100,,92,93,,,106,101,112,91,115,,109,,111,,102,104',
'103,105,,,,,,,,,,,,,98,,,114,,,,108,107,,110,94,95,97,96,99,100,,92',
'93,,,106,101,112,91,115,,109,,111,,102,104,103,105,,,,,,,,,,,,,98,,',
'114,,,,108,107,,110,94,95,97,96,99,100,,92,93,,,106,101,112,91,115,',
'109,,111,,102,104,103,105,,,,,,,,,,,,,98,,,114,,,,108,107,,110,94,95',
'97,96,99,100,,92,93,,,106,101,112,91,115,,109,,111,,102,104,103,105',
',,,,,,,,,,,,98,,,114,,,,108,107,,110,94,95,97,96,99,100,,92,93,,,106',
'101,112,91,115,,109,,111,,102,104,103,105,,,,,,,,,,,,,98,,,114,,,,108',
'107,,,94,95,97,96,99,100,,92,93,,340,219,339,220,91,337,222,341,,334',
',336,338,,,,,,,223,218,342,,,,335,,98,,,,,,,,,,221,343,,,,,,,,,,,,346',
'344,347,345,348,349,340,219,339,220,,337,222,341,,334,,336,338,,,,,',
',223,218,342,,,,335,,,,,,,,,,,,221,343,,,,,,,,,,,,346,344,347,345,348',
'349,340,219,339,220,,337,222,341,,334,,336,338,,,,,,,223,218,342,,,',
'335,,,,,,,,,,,,221,343,,,,,,,,,,,,346,344,347,345,348,349,340,219,339',
'220,,337,222,341,,334,,336,338,,,,,,,223,218,342,,,,335,,,,,,,,,,,,221',
'343,,,,,,,,,,,,346,344,347,345,348,349' ]
racc_action_table = arr = ::Array.new(9957, nil)
idx = 0
clist.each do |str|
str.split(',', -1).each do |i|
arr[idx] = i.to_i unless i.empty?
idx += 1
end
end
clist = [
'0,0,285,200,0,0,1,0,7,7,7,166,225,166,201,286,174,296,298,174,298,202',
'209,285,0,0,225,216,225,217,286,0,225,0,5,0,0,112,0,0,0,144,0,0,0,0',
'200,8,0,0,296,49,0,225,166,0,0,201,7,7,7,7,54,0,202,209,54,48,50,0,216',
'144,217,0,0,225,0,0,0,112,56,0,0,0,0,0,0,4,4,0,48,4,4,372,4,166,383',
'12,54,226,59,12,54,147,12,383,372,379,73,379,54,4,4,226,372,226,147',
'55,4,226,4,55,4,4,147,4,4,4,4,4,4,4,4,12,74,4,4,12,147,4,226,365,4,4',
'58,12,365,127,58,79,4,127,81,55,138,113,4,55,138,137,4,4,226,4,4,55',
'119,119,4,4,4,4,4,4,10,10,4,116,10,10,58,10,137,127,58,210,470,127,203',
'210,138,470,58,117,138,127,211,130,10,10,211,437,138,437,131,10,132',
'10,135,10,10,203,10,10,10,136,10,10,10,10,139,210,10,10,142,210,10,153',
'153,10,10,213,211,210,215,213,211,10,215,154,154,357,146,10,211,357',
'156,10,10,158,10,10,165,165,167,10,10,10,10,10,10,11,11,10,170,11,11',
'213,11,172,215,213,182,182,215,188,182,357,193,213,194,357,215,195,357',
'11,11,179,179,357,404,404,11,196,11,198,11,11,126,11,11,11,212,11,11',
'11,11,247,254,11,11,256,126,11,126,257,11,11,126,57,57,260,267,57,11',
'272,273,274,277,283,11,284,291,292,11,11,293,11,11,126,294,297,11,11',
'11,11,11,11,16,16,11,301,16,16,128,16,303,315,320,57,321,323,57,329',
'331,333,335,352,128,355,128,359,16,16,128,361,363,366,367,16,370,16',
'57,16,16,129,16,16,16,371,16,16,57,57,378,128,16,16,380,129,16,129,381',
'16,16,129,214,214,388,389,214,16,394,403,405,412,416,16,419,424,425',
'16,16,431,16,16,129,440,441,16,16,16,16,16,16,17,17,16,443,17,17,224',
'17,445,448,451,214,452,456,214,459,184,460,465,468,224,481,224,483,17',
'17,224,484,490,184,492,17,494,17,214,17,17,184,17,17,17,497,17,17,214',
'214,502,224,17,17,,184,17,,,17,17,,295,295,,,295,17,,,,,,17,,,,17,17',
',17,17,,,,17,17,17,17,17,17,18,18,17,,18,18,,18,,,,295,,,295,,,,,,,',
',,18,18,,,262,,,18,263,18,295,18,18,262,18,18,18,263,18,18,295,295,',
',18,18,262,,18,,263,18,18,,262,,,,263,18,,,,,,18,,,,18,18,,18,18,,,',
'18,18,18,18,18,18,19,19,18,,19,19,,19,,,,,,,,,,,,,,,,,19,19,,,,,,19',
',19,,19,19,,19,19,19,,19,19,19,19,,,19,19,,,19,,,19,19,,,,,,,19,,,,',
',19,,,,19,19,,19,19,,,,19,19,19,19,19,19,20,20,19,,20,20,,20,,,,,,,',
',,,,,,,,,20,20,,,,,,20,,20,,20,20,,20,20,20,,20,20,20,20,,,20,20,,,20',
',,20,20,,,,,,,20,,,,,,20,,,,20,20,,20,20,,,,20,20,20,20,20,20,47,47',
'20,,47,47,,47,,,,,,,,,,,,,,,,,47,47,47,,,,,47,,47,,47,47,,47,47,47,',
'47,47,47,47,,,47,47,,,47,,,47,47,,391,391,,,391,47,,,,,,47,,,,47,47',
',47,47,,,,47,47,47,47,47,47,51,51,47,,51,51,,51,,,,391,,,391,,,,,,,',
',,51,51,,,,,,51,,51,391,51,51,,51,51,51,,51,51,391,391,,,51,51,,,51',
',,51,51,,,,,,,51,,,,,,51,,,,51,51,,51,51,,,,51,51,51,51,51,51,52,52',
'51,229,52,52,,52,,,,,,,,,,229,,229,,,,229,52,52,,,,,,52,,52,,52,52,',
'52,52,52,,52,52,229,,,,52,52,,,52,,,52,52,,,229,229,,,52,,,229,,,52',
',,,52,52,,52,52,,,,52,52,52,52,52,52,53,53,52,230,53,53,,53,,,,,,,,',
',230,,230,,,,230,53,53,,,,,,53,,53,,53,53,,53,53,53,,53,53,230,,,,53',
'53,,,53,,,53,53,,,230,230,,,53,,,230,,,53,,,,53,53,,53,53,,,,53,53,53',
'53,53,53,63,63,53,,63,63,63,63,,,,,,,,,,,,,,,,,63,63,,,,,,63,,63,,63',
'63,,63,63,63,,63,63,63,63,,,63,63,,,63,,,63,63,,,,,,,63,,,,,,63,,,,63',
'63,,63,63,,,,63,63,63,63,63,63,64,64,63,,64,64,64,64,,,,,,,,,,,,,,,',
',64,64,,,,,,64,,64,,64,64,,64,64,64,,64,64,64,64,,,64,64,,,64,,,64,64',
',,,,,,64,,,,,,64,,,,64,64,,64,64,,,,64,64,64,64,64,64,65,65,64,,65,65',
',65,65,,,,,,,,,,,,,,,,65,65,,,,,,65,,65,,65,65,,65,65,65,,65,65,65,65',
',,65,65,,,65,,,65,65,,,,,,,65,,,,,,65,,,,65,65,,65,65,,,,65,65,65,65',
'65,65,71,71,65,,71,71,,71,,,,,,,,,,,,,,,,,71,71,,,,,,71,,71,,71,71,',
'71,71,71,,71,71,71,71,,,71,71,,,71,,,71,71,,,,,,,71,,,,,,71,,,,71,71',
',71,71,,,,71,71,71,71,71,71,76,76,71,231,76,76,,76,,,,,,,,,,231,,231',
',,,231,76,76,,,,,,76,,76,,76,76,,76,76,76,,76,76,231,,,,76,76,,,76,',
',76,76,,,231,231,,,76,,,231,,,76,,,,76,76,,76,76,,,,76,76,76,76,76,76',
'80,80,76,,80,80,,80,,,,,,,,,,,,,,,,,80,80,,,,,,80,,80,,80,80,,80,80',
'80,,80,80,80,80,,,80,80,,,80,,,80,80,,,,,,,80,,,,,,80,,,,80,80,,80,80',
',,,80,80,80,80,80,80,82,82,80,,82,82,,82,,,,,,,,,,,,,,,,,82,82,,,,,',
'82,,82,,82,82,,82,82,82,,82,82,82,82,,,82,82,,,82,,,82,82,,,,,,,82,',
',,,,82,,,,82,82,,82,82,,,,82,82,82,82,82,82,83,83,82,,83,83,,83,,,,',
',,,,,,,,,,,,83,83,,,,,,83,,83,,83,83,,83,83,83,,83,83,83,83,,,83,83',
',,83,,,83,83,,,,,,,83,,,,,,83,,,,83,83,,83,83,,,,83,83,83,83,83,83,84',
'84,83,,84,84,,84,,,,,,,,,,,,,,,,,84,84,,,,,,84,,84,,84,84,,84,84,84',
',84,84,84,84,,,84,84,,,84,,,84,84,,,,,,,84,,,,,,84,,,,84,84,,84,84,',
',,84,84,84,84,84,84,85,85,84,,85,85,,85,,,,,,,,,,,,,,,,,85,85,,,,,,85',
',85,,85,85,,85,85,85,,85,85,85,85,,,85,85,,,85,,,85,85,,,,,,,85,,,,',
',85,,,,85,85,,85,85,,,,85,85,85,85,85,85,86,86,85,,86,86,,86,,,,,,,',
',,,,,,,,,86,86,,,,,,86,,86,,86,86,,86,86,86,,86,86,86,86,,,86,86,,,86',
',,86,86,,,,,,,86,,,,,,86,,,,86,86,,86,86,,,,86,86,86,86,86,86,87,87',
'86,,87,87,,87,,,,,,,,,,,,,,,,,87,87,,,,,,87,,87,,87,87,,87,87,87,,87',
'87,87,87,,,87,87,,,87,,,87,87,,,,,,,87,,,,,,87,,,,87,87,,87,87,,,,87',
'87,87,87,87,87,88,88,87,,88,88,,88,,,,,,,,,,,,,,,,,88,88,,,,,,88,,88',
',88,88,,88,88,88,,88,88,88,88,,,88,88,,,88,,,88,88,,,,,,,88,,,,,,88',
',,,88,88,,88,88,,,,88,88,88,88,88,88,89,89,88,,89,89,,89,,,,,,,,,,,',
',,,,,89,89,,,,,,89,,89,,89,89,,89,89,89,,89,89,89,89,,,89,89,,,89,,',
'89,89,,,,,,,89,,,,,,89,,,,89,89,,89,89,,,,89,89,89,89,89,89,90,90,89',
',90,90,,90,,,,,,,,,,,,,,,,,90,90,,,,,,90,90,90,90,90,90,90,90,90,90',
',90,90,,,,,90,90,90,90,90,,,90,90,,,,,,,90,,,,,90,90,,,,90,90,,90,90',
',,,90,90,90,90,90,90,91,91,90,,91,91,,91,,,,,,,,,,,,,,,,,91,91,,,,,',
'91,,91,,91,91,,91,91,91,,91,91,,,,,91,91,,,91,,,91,91,,,,,,,91,,,,,',
'91,,,,91,91,,91,91,,,,91,91,91,91,91,91,92,92,91,,92,92,,92,,,,,,,,',
',,,,,,,,92,92,,,,,,92,,92,,92,92,,92,92,92,,92,92,,,,,92,92,,,92,,,92',
'92,,,,,,,92,,,,,,92,,,,92,92,,92,92,,,,92,92,92,92,92,92,93,93,92,,93',
'93,,93,,,,,,,,,,,,,,,,,93,93,,,,,,93,,93,,93,93,,93,93,93,,93,93,,,',
',93,93,,,93,,,93,93,,,,,,,93,,,,,,93,,,,93,93,,93,93,,,,93,93,93,93',
'93,93,94,94,93,,94,94,,94,,,,,,,,,,,,,,,,,94,94,,,,,,94,,94,,94,94,',
'94,94,94,,94,94,,,,,94,94,,,94,,,94,94,,,,,,,94,,,,,,94,,,,94,94,,94',
'94,,,,94,94,94,94,94,94,95,95,94,,95,95,,95,,,,,,,,,,,,,,,,,95,95,,',
',,,95,,95,,95,95,,95,95,95,,95,95,,,,,95,95,,,95,,,95,95,,,,,,,95,,',
',,,95,,,,95,95,,95,95,,,,95,95,95,95,95,95,96,96,95,,96,96,,96,,,,,',
',,,,,,,,,,,96,96,,,,,,96,,96,,96,96,,96,96,96,,96,96,,,,,96,96,,,96',
',,96,96,,,,,,,96,,,,,,96,,,,96,96,,96,96,,,,96,96,96,96,96,96,97,97',
'96,,97,97,,97,,,,,,,,,,,,,,,,,97,97,,,,,,97,,97,,97,97,,97,97,97,,97',
'97,,,,,97,97,,,97,,,97,97,,,,,,,97,,,,,,97,,,,97,97,,97,97,,,,97,97',
'97,97,97,97,98,98,97,,98,98,,98,,,,,,,,,,,,,,,,,98,98,,,,,,98,,98,,98',
'98,,98,98,98,,98,98,,,,,98,98,,,98,,,98,98,,,,,,,98,,,,,,98,,,,98,98',
',98,98,,,,98,98,98,98,98,98,99,99,98,,99,99,,99,,,,,,,,,,,,,,,,,99,99',
',,,,,99,,99,,99,99,,99,99,99,,99,99,,,,,99,99,,,99,,,99,99,,,,,,,99',
',,,,,99,,,,99,99,,99,99,,,,99,99,99,99,99,99,100,100,99,,100,100,,100',
',,,,,,,,,,,,,,,,100,100,,,,,,100,,100,,100,100,,100,100,100,,100,100',
',,,,100,100,,,100,,,100,100,,,,,,,100,,,,,,100,,,,100,100,,100,100,',
',,100,100,100,100,100,100,101,101,100,,101,101,,101,,,,,,,,,,,,,,,,',
'101,101,,,,,,101,,101,,101,101,,101,101,101,,101,101,,,,,101,101,,,101',
',,101,101,,,,,,,101,,,,,,101,,,,101,101,,101,101,,,,101,101,101,101',
'101,101,102,102,101,,102,102,,102,,,,,,,,,,,,,,,,,102,102,,,,,,102,',
'102,,102,102,,102,102,102,,102,102,,,,,102,102,,,102,,,102,102,,,,,',
',102,,,,,,102,,,,102,102,,102,102,,,,102,102,102,102,102,102,103,103',
'102,,103,103,,103,,,,,,,,,,,,,,,,,103,103,,,,,,103,,103,,103,103,,103',
'103,103,,103,103,,,,,103,103,,,103,,,103,103,,,,,,,103,,,,,,103,,,,103',
'103,,103,103,,,,103,103,103,103,103,103,104,104,103,,104,104,,104,,',
',,,,,,,,,,,,,,104,104,,,,,,104,,104,,104,104,,104,104,104,,104,104,',
',,,104,104,,,104,,,104,104,,,,,,,104,,,,,,104,,,,104,104,,104,104,,',
',104,104,104,104,104,104,105,105,104,,105,105,,105,,,,,,,,,,,,,,,,,105',
'105,,,,,,105,,105,,105,105,,105,105,105,,105,105,,,,,105,105,,,105,',
',105,105,,,,,,,105,,,,,,105,,,,105,105,,105,105,,,,105,105,105,105,105',
'105,106,106,105,,106,106,,106,,,,,,,,,,,,,,,,,106,106,,,,,,106,,106',
',106,106,,106,106,106,,106,106,,,,,106,106,,,106,,,106,106,,,,,,,106',
',,,,,106,,,,106,106,,106,106,,,,106,106,106,106,106,106,107,107,106',
',107,107,,107,,,,,,,,,,,,,,,,,107,107,,,,,,107,,107,,107,107,,107,107',
'107,,107,107,,,,,107,107,,,107,,,107,107,,,,,,,107,,,,,,107,,,,107,107',
',107,107,,,,107,107,107,107,107,107,108,108,107,,108,108,,108,,,,,,',
',,,,,,,,,,108,108,,,,,,108,,108,,108,108,,108,108,108,,108,108,,,,,108',
'108,,,108,,,108,108,,,,,,,108,,,,,,108,,,,108,108,,108,108,,,,108,108',
'108,108,108,108,109,109,108,,109,109,,109,,,,,,,,,,,,,,,,,109,109,,',
',,,109,,109,,109,109,,109,109,109,,109,109,,,,,109,109,,,109,,,109,109',
',,,,,,109,,,,,,109,,,109,109,109,,109,109,,,,109,109,109,109,109,109',
'110,110,109,,110,110,,110,,,,,,,,,,,,,,,,,110,110,,,,,,110,,110,,110',
'110,,110,110,110,,110,110,110,110,,,110,110,,,110,,,110,110,,,,,,,110',
',,,,,110,,,,110,110,,110,110,,,,110,110,110,110,110,110,114,114,110',
',114,114,,114,,,,,,,,,,,,,,,,,114,114,,,,,,114,,114,,114,114,,114,114',
'114,,114,114,,,,,114,114,,,114,,,114,114,,,,,,,114,,,,,,114,,,,114,114',
',114,114,,,,114,114,114,114,114,114,115,115,114,,115,115,,115,,,,,,',
',,,,,,,,,,115,115,,,,,,115,,115,,115,115,,115,115,115,,115,115,,,,,115',
'115,,,115,,,115,115,,,,,,,115,,,,,,115,,,,115,115,,115,115,,,,115,115',
'115,115,115,115,118,118,115,,118,118,,118,,,,,,,,,,,,,,,,,118,118,,',
',,,118,,118,,118,118,,118,118,118,,118,118,,,,,118,118,,,118,,,118,118',
',,,,,,118,,,,,,118,,,,118,118,,118,118,,,,118,118,118,118,118,118,148',
'148,118,,148,148,,148,,,,,,,,,,,,,,,,,148,148,148,,,,,148,,148,,148',
'148,,148,148,148,,148,148,148,148,,,148,148,,,148,,,148,148,,,,,,,148',
',,,,,148,,,,148,148,,148,148,,,,148,148,148,148,148,148,155,155,148',
',155,155,,155,,,,,,,,,,,,,,,,,155,155,,,,,,155,,155,,155,155,,155,155',
'155,,155,155,155,155,,,155,155,,,155,,,155,155,,,,,,,155,,,,,,155,,',
',155,155,,155,155,,,,155,155,155,155,155,155,183,183,155,,183,183,,183',
',,,,,,,,,,,,,,,,183,183,,,,,,183,,183,,183,183,,183,183,183,,183,183',
'183,183,,,183,183,,,183,,,183,183,,,,,,,183,,,,,,183,,,,183,183,,183',
'183,,,,183,183,183,183,183,183,186,186,183,,186,186,,186,186,,,,,,,',
',,,,,,,,186,186,,,,,,186,,186,,186,186,,186,186,186,,186,186,186,186',
',,186,186,,,186,,,186,186,,,,,,,186,,,,,,186,,,,186,186,,186,186,,,',
'186,186,186,186,186,186,199,199,186,,199,199,,199,,,199,,,,,,,,,,,,',
',199,199,,,,,,199,,199,,199,199,,199,199,199,,199,199,,,,,199,199,,',
'199,,,199,199,,,,,,,199,,,,,,199,,,,199,199,,199,199,,,,199,199,199',
'199,199,199,204,204,199,,204,204,,204,,,,,,,,,,,,,,,,,204,204,,,,,,204',
',204,,204,204,,204,204,204,,204,204,,,,,204,204,,,204,,,204,204,,,,',
',,204,,,,,,204,,,,204,204,,204,204,,,,204,204,204,204,204,204,205,205',
'204,,205,205,,205,,,,,,,,,,,,,,,,,205,205,,,,,,205,,205,,205,205,,205',
'205,205,,205,205,,,,,205,205,,,205,,,205,205,,,,,,,205,,,,,,205,,,,205',
'205,,205,205,,,,205,205,205,205,205,205,206,206,205,,206,206,,206,,',
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/parser/code_merger.rb | lib/puppet/pops/parser/code_merger.rb | # frozen_string_literal: true
class Puppet::Pops::Parser::CodeMerger
# Concatenates the logic in the array of parse results into one parse result.
# @return Puppet::Parser::AST::BlockExpression
#
def concatenate(parse_results)
# this is a bit brute force as the result is already 3x ast with wrapped 4x content
# this could be combined in a more elegant way, but it is only used to process a handful of files
# at the beginning of a puppet run. TODO: Revisit for Puppet 4x when there is no 3x ast at the top.
# PUP-5299, some sites have thousands of entries, and run out of stack when evaluating - the logic
# below maps the logic as flatly as possible.
#
children = parse_results.select { |x| !x.nil? && x.code }.flat_map do |parsed_class|
case parsed_class.code
when Puppet::Parser::AST::BlockExpression
# the BlockExpression wraps a single 4x instruction that is most likely wrapped in a Factory
parsed_class.code.children.map { |c| c.is_a?(Puppet::Pops::Model::Factory) ? c.model : c }
when Puppet::Pops::Model::Factory
# If it is a 4x instruction wrapped in a Factory
parsed_class.code.model
else
# It is the instruction directly
parsed_class.code
end
end
Puppet::Parser::AST::BlockExpression.new(:children => children)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/parser/locator.rb | lib/puppet/pops/parser/locator.rb | # frozen_string_literal: true
module Puppet::Pops
module Parser
# Helper class that keeps track of where line breaks are located and can answer questions about positions.
#
class Locator
# Creates, or recreates a Locator. A Locator is created if index is not given (a scan is then
# performed of the given source string.
#
def self.locator(string, file, index = nil, char_offsets = false)
if char_offsets
LocatorForChars.new(string, file, index)
else
Locator19.new(string, file, index)
end
end
# Returns the file name associated with the string content
def file
end
# Returns the string content
def string
end
def to_s
"Locator for file #{file}"
end
# Returns the position on line (first position on a line is 1)
def pos_on_line(offset)
end
# Returns the line number (first line is 1) for the given offset
def line_for_offset(offset)
end
# Returns the offset on line (first offset on a line is 0).
#
def offset_on_line(offset)
end
# Returns the character offset for a given reported offset
def char_offset(byte_offset)
end
# Returns the length measured in number of characters from the given start and end byte offset
def char_length(offset, end_offset)
end
# Extracts the text from offset with given length (measured in what the locator uses for offset)
# @returns String - the extracted text
def extract_text(offset, length)
end
def extract_tree_text(ast)
first = ast.offset
last = first + ast.length
ast._pcore_all_contents([]) do |m|
next unless m.is_a?(Model::Positioned)
m_offset = m.offset
m_last = m_offset + m.length
first = m_offset if m_offset < first
last = m_last if m_last > last
end
extract_text(first, last - first)
end
# Returns the line index - an array of line offsets for the start position of each line, starting at 0 for
# the first line.
#
def line_index
end
# Common byte based impl that works for all rubies (stringscanner is byte based
def self.compute_line_index(string)
scanner = StringScanner.new(string)
result = [0] # first line starts at 0
while scanner.scan_until(/\n/)
result << scanner.pos
end
result.freeze
end
# Produces an URI with path?line=n&pos=n. If origin is unknown the URI is string:?line=n&pos=n
def to_uri(ast)
f = file
if f.nil? || f.empty?
f = 'string:'
else
f = Puppet::Util.path_to_uri(f).to_s
end
offset = ast.offset
URI("#{f}?line=#{line_for_offset(offset)}&pos=#{pos_on_line(offset)}")
end
class AbstractLocator < Locator
attr_accessor :line_index
attr_reader :string
attr_reader :file
# Create a locator based on a content string, and a boolean indicating if ruby version support multi-byte strings
# or not.
#
def initialize(string, file, line_index = nil)
@string = string.freeze
@file = file.freeze
@prev_offset = nil
@prev_line = nil
@line_index = line_index.nil? ? Locator.compute_line_index(@string) : line_index
end
# Returns the position on line (first position on a line is 1)
def pos_on_line(offset)
offset_on_line(offset) + 1
end
def to_location_hash(reported_offset, end_offset)
pos = pos_on_line(reported_offset)
offset = char_offset(reported_offset)
length = char_length(reported_offset, end_offset)
start_line = line_for_offset(reported_offset)
{ :line => start_line, :pos => pos, :offset => offset, :length => length }
end
# Returns the index of the smallest item for which the item > the given value
# This is a min binary search. Although written in Ruby it is only slightly slower than
# the corresponding method in C in Ruby 2.0.0 - the main benefit to use this method over
# the Ruby C version is that it returns the index (not the value) which means there is not need
# to have an additional structure to get the index (or record the index in the structure). This
# saves both memory and CPU. It also does not require passing a block that is called since this
# method is specialized to search the line index.
#
def ary_bsearch_i(ary, value)
low = 0
high = ary.length
mid = nil
smaller = false
satisfied = false
v = nil
while low < high
mid = low + ((high - low) / 2)
v = (ary[mid] > value)
if v == true
satisfied = true
smaller = true
elsif !v
smaller = false
else
raise TypeError, "wrong argument, must be boolean or nil, got '#{v.class}'"
end
if smaller
high = mid
else
low = mid + 1;
end
end
return nil if low == ary.length
return nil unless satisfied
low
end
def hash
[string, file, line_index].hash
end
# Equal method needed by serializer to perform tabulation
def eql?(o)
self.class == o.class && string == o.string && file == o.file && line_index == o.line_index
end
# Returns the line number (first line is 1) for the given offset
def line_for_offset(offset)
if @prev_offset == offset
# use cache
return @prev_line
end
line_nbr = ary_bsearch_i(line_index, offset)
if line_nbr
# cache
@prev_offset = offset
@prev_line = line_nbr
return line_nbr
end
# If not found it is after last
# clear cache
@prev_offset = @prev_line = nil
line_index.size
end
end
# A Sublocator locates a concrete locator (subspace) in a virtual space.
# The `leading_line_count` is the (virtual) number of lines preceding the first line in the concrete locator.
# The `leading_offset` is the (virtual) byte offset of the first byte in the concrete locator.
# The `leading_line_offset` is the (virtual) offset / margin in characters for each line.
#
# This illustrates characters in the sublocator (`.`) inside the subspace (`X`):
#
# 1:XXXXXXXX
# 2:XXXX.... .. ... ..
# 3:XXXX. . .... ..
# 4:XXXX............
#
# This sublocator would be configured with leading_line_count = 1,
# leading_offset=8, and leading_line_offset=4
#
# Note that leading_offset must be the same for all lines and measured in characters.
#
# A SubLocator is only used during parsing as the parser will translate the local offsets/lengths to
# the parent locator when a sublocated expression is reduced. Do not call the methods
# `char_offset` or `char_length` as those methods will raise an error.
#
class SubLocator < AbstractLocator
attr_reader :locator
attr_reader :leading_line_count
attr_reader :leading_offset
attr_reader :has_margin
attr_reader :margin_per_line
def initialize(locator, str, leading_line_count, leading_offset, has_margin, margin_per_line)
super(str, locator.file)
@locator = locator
@leading_line_count = leading_line_count
@leading_offset = leading_offset
@has_margin = has_margin
@margin_per_line = margin_per_line
# Since lines can have different margin - accumulated margin per line must be computed
# and since this accumulated margin adjustment is needed more than once; both for start offset,
# and for end offset (to compute global length) it is computed up front here.
# The accumulated_offset holds the sum of all removed margins before a position on line n (line index is 1-n,
# and (unused) position 0 is always 0).
# The last entry is duplicated since there will be the line "after last line" that would otherwise require
# conditional logic.
#
@accumulated_margin = margin_per_line.each_with_object([0]) { |val, memo| memo << memo[-1] + val; }
@accumulated_margin << @accumulated_margin[-1]
end
def file
@locator.file
end
# Returns array with transposed (local) offset and (local) length. The transposed values
# take the margin into account such that it is added to the content to the right
#
# Using X to denote margin and where end of line is explicitly shown as \n:
# ```
# XXXXabc\n
# XXXXdef\n
# ```
# A local offset of 0 is translated to the start of the first heredoc line, and a length of 1 is adjusted to
# 5 - i.e to cover "XXXXa". A local offset of 1, with length 1 would cover "b".
# A local offset of 4 and length 1 would cover "XXXXd"
#
# It is possible that lines have different margin and that is taken into account.
#
def to_global(offset, length)
# simple case, no margin
return [offset + @leading_offset, length] unless @has_margin
# compute local start and end line
start_line = line_for_offset(offset)
end_line = line_for_offset(offset + length)
# complex case when there is a margin
transposed_offset = offset == 0 ? @leading_offset : offset + @leading_offset + @accumulated_margin[start_line]
transposed_length = length +
@accumulated_margin[end_line] - @accumulated_margin[start_line] + # the margins between start and end (0 is line 1)
(offset_on_line(offset) == 0 ? margin_per_line[start_line - 1] : 0) # include start's margin in position 0
[transposed_offset, transposed_length]
end
# Do not call this method
def char_offset(offset)
raise "Should not be called"
end
# Do not call this method
def char_length(offset, end_offset)
raise "Should not be called"
end
end
class LocatorForChars < AbstractLocator
def offset_on_line(offset)
line_offset = line_index[line_for_offset(offset) - 1]
offset - line_offset
end
def char_offset(char_offset)
char_offset
end
def char_length(offset, end_offset)
end_offset - offset
end
# Extracts the text from char offset with given byte length
# @returns String - the extracted text
def extract_text(offset, length)
string.slice(offset, length)
end
end
# This implementation is for Ruby19 and Ruby20. It uses byteslice to get strings from byte based offsets.
# For Ruby20 this is faster than using the Stringscanner.charpos method (byteslice outperforms it, when
# strings are frozen).
#
class Locator19 < AbstractLocator
include Types::PuppetObject
# rubocop:disable Naming/MemoizedInstanceVariableName
def self._pcore_type
@type ||= Types::PObjectType.new('Puppet::AST::Locator', {
'attributes' => {
'string' => Types::PStringType::DEFAULT,
'file' => Types::PStringType::DEFAULT,
'line_index' => {
Types::KEY_TYPE => Types::POptionalType.new(Types::PArrayType.new(Types::PIntegerType::DEFAULT)),
Types::KEY_VALUE => nil
}
}
})
end
# rubocop:enable Naming/MemoizedInstanceVariableName
# Returns the offset on line (first offset on a line is 0).
# Ruby 19 is multibyte but has no character position methods, must use byteslice
def offset_on_line(offset)
line_offset = line_index[line_for_offset(offset) - 1]
@string.byteslice(line_offset, offset - line_offset).length
end
# Returns the character offset for a given byte offset
# Ruby 19 is multibyte but has no character position methods, must use byteslice
def char_offset(byte_offset)
string.byteslice(0, byte_offset).length
end
# Returns the length measured in number of characters from the given start and end byte offset
def char_length(offset, end_offset)
string.byteslice(offset, end_offset - offset).length
end
# Extracts the text from byte offset with given byte length
# @returns String - the extracted text
def extract_text(offset, length)
string.byteslice(offset, length)
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/parser/slurp_support.rb | lib/puppet/pops/parser/slurp_support.rb | # frozen_string_literal: true
module Puppet::Pops
module Parser
# This module is an integral part of the Lexer.
# It defines the string slurping behavior - finding the string and non string parts in interpolated
# strings, translating escape sequences in strings to their single character equivalence.
#
# PERFORMANCE NOTE: The various kinds of slurping could be made even more generic, but requires
# additional parameter passing and evaluation of conditional logic.
# TODO: More detailed performance analysis of excessive character escaping and interpolation.
#
module SlurpSupport
include LexerSupport
SLURP_SQ_PATTERN = /(?:[^\\]|^)(?:\\{2})*'/
SLURP_DQ_PATTERN = /(?:[^\\]|^)(?:\\{2})*("|[$]\{?)/
SLURP_UQ_PATTERN = /(?:[^\\]|^)(?:\\{2})*([$]\{?|\z)/
# unquoted, no escapes
SLURP_UQNE_PATTERN = /(\$\{?|\z)/m
SLURP_ALL_PATTERN = /.*(\z)/m
SQ_ESCAPES = %w[\\ ']
DQ_ESCAPES = %w[\\ $ ' " r n t s u] + ["\r\n", "\n"]
UQ_ESCAPES = %w[\\ $ r n t s u] + ["\r\n", "\n"]
def slurp_sqstring
# skip the leading '
@scanner.pos += 1
str = slurp(@scanner, SLURP_SQ_PATTERN, SQ_ESCAPES, :ignore_invalid_escapes)
lex_error(Issues::UNCLOSED_QUOTE, :after => "\"'\"", :followed_by => followed_by) unless str
str[0..-2] # strip closing "'" from result
end
def slurp_dqstring
scn = @scanner
last = scn.matched
str = slurp(scn, SLURP_DQ_PATTERN, DQ_ESCAPES, false)
unless str
lex_error(Issues::UNCLOSED_QUOTE, :after => format_quote(last), :followed_by => followed_by)
end
# Terminator may be a single char '"', '$', or two characters '${' group match 1 (scn[1]) from the last slurp holds this
terminator = scn[1]
[str[0..(-1 - terminator.length)], terminator]
end
# Copy from old lexer - can do much better
def slurp_uqstring
scn = @scanner
str = slurp(scn, @lexing_context[:uq_slurp_pattern], @lexing_context[:escapes], :ignore_invalid_escapes)
# Terminator may be a single char '$', two characters '${', or empty string '' at the end of intput.
# Group match 1 holds this.
# The exceptional case is found by looking at the subgroup 1 of the most recent match made by the scanner (i.e. @scanner[1]).
# This is the last match made by the slurp method (having called scan_until on the scanner).
# If there is a terminating character is must be stripped and returned separately.
#
terminator = scn[1]
[str[0..(-1 - terminator.length)], terminator]
end
# Slurps a string from the given scanner until the given pattern and then replaces any escaped
# characters given by escapes into their control-character equivalent or in case of line breaks, replaces the
# pattern \r?\n with an empty string.
# The returned string contains the terminating character. Returns nil if the scanner can not scan until the given
# pattern.
#
def slurp(scanner, pattern, escapes, ignore_invalid_escapes)
str = scanner.scan_until(pattern) || return
return str unless str.include?('\\')
return str.gsub!(/\\(\\|')/m, '\1') || str if escapes.equal?(SQ_ESCAPES)
# Process unicode escapes first as they require getting 4 hex digits
# If later a \u is found it is warned not to be a unicode escape
if escapes.include?('u')
# gsub must be repeated to cater for adjacent escapes
while str.gsub!(/((?:[^\\]|^)(?:\\{2})*)\\u(?:([\da-fA-F]{4})|\{([\da-fA-F]{1,6})\})/m) { ::Regexp.last_match(1) + [(::Regexp.last_match(2) || ::Regexp.last_match(3)).hex].pack("U") }
# empty block. Everything happens in the gsub block
end
end
begin
str.gsub!(/\\([^\r\n]|(?:\r?\n))/m) {
ch = ::Regexp.last_match(1)
if escapes.include? ch
case ch
when 'r'; "\r"
when 'n'; "\n"
when 't'; "\t"
when 's'; ' '
when 'u'
lex_warning(Issues::ILLEGAL_UNICODE_ESCAPE)
"\\u"
when "\n"; ''
when "\r\n"; ''
else ch
end
else
lex_warning(Issues::UNRECOGNIZED_ESCAPE, :ch => ch) unless ignore_invalid_escapes
"\\#{ch}"
end
}
rescue ArgumentError => e
# A invalid byte sequence may be the result of faulty input as well, but that could not possibly
# have reached this far... Unfortunately there is no more specific error and a match on message is
# required to differentiate from other internal problems.
if e.message =~ /invalid byte sequence/
lex_error(Issues::ILLEGAL_UNICODE_ESCAPE)
else
raise e
end
end
str
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/parser/evaluating_parser.rb | lib/puppet/pops/parser/evaluating_parser.rb | # frozen_string_literal: true
require_relative '../../../puppet/concurrent/thread_local_singleton'
module Puppet::Pops
module Parser
# Does not support "import" and parsing ruby files
#
class EvaluatingParser
extend Puppet::Concurrent::ThreadLocalSingleton
attr_reader :parser
def initialize
@parser = Parser.new()
end
def parse_string(s, file_source = nil)
clear()
# Handling of syntax error can be much improved (in general), now it bails out of the parser
# and does not have as rich information (when parsing a string), need to update it with the file source
# (ideally, a syntax error should be entered as an issue, and not just thrown - but that is a general problem
# and an improvement that can be made in the eparser (rather than here).
# Also a possible improvement (if the YAML parser returns positions) is to provide correct output of position.
#
begin
assert_and_report(parser.parse_string(s, file_source), file_source).model
rescue Puppet::ParseErrorWithIssue => e
raise e
rescue Puppet::ParseError => e
# TODO: This is not quite right, why does not the exception have the correct file?
e.file = file_source unless e.file.is_a?(String) && !e.file.empty?
raise e
end
end
def parse_file(file)
clear()
assert_and_report(parser.parse_file(file), file).model
end
def evaluate_string(scope, s, file_source = nil)
evaluate(scope, parse_string(s, file_source))
end
def evaluate_file(scope, file)
evaluate(scope, parse_file(file))
end
def clear
@acceptor = nil
end
# Create a closure that can be called in the given scope
def closure(model, scope)
Evaluator::Closure::Dynamic.new(evaluator, model, scope)
end
def evaluate(scope, model)
return nil unless model
evaluator.evaluate(model, scope)
end
# Evaluates the given expression in a local scope with the given variable bindings
# set in this local scope, returns what the expression returns.
#
def evaluate_expression_with_bindings(scope, variable_bindings, expression)
evaluator.evaluate_block_with_bindings(scope, variable_bindings, expression)
end
def evaluator
# Do not use the cached evaluator if this is a migration run
if Puppet.lookup(:migration_checker) { nil }
return Evaluator::EvaluatorImpl.new()
end
@@evaluator ||= Evaluator::EvaluatorImpl.new()
@@evaluator
end
def convert_to_3x(object, scope)
evaluator.convert(object, scope, nil)
end
def validate(parse_result)
resulting_acceptor = acceptor()
validator(resulting_acceptor).validate(parse_result)
resulting_acceptor
end
def acceptor
Validation::Acceptor.new
end
def validator(acceptor)
Validation::ValidatorFactory_4_0.new().validator(acceptor)
end
def assert_and_report(parse_result, file_source)
return nil unless parse_result
if parse_result['source_ref'].nil? || parse_result['source_ref'] == ''
parse_result['source_ref'] = file_source
end
validation_result = validate(parse_result.model)
IssueReporter.assert_and_report(validation_result,
:emit_warnings => true)
parse_result
end
def quote(x)
self.class.quote(x)
end
# Translates an already parsed string that contains control characters, quotes
# and backslashes into a quoted string where all such constructs have been escaped.
# Parsing the return value of this method using the puppet parser should yield
# exactly the same string as the argument passed to this method
#
# The method makes an exception for the two character sequences \$ and \s. They
# will not be escaped since they have a special meaning in puppet syntax.
#
# TODO: Handle \uXXXX characters ??
#
# @param x [String] The string to quote and "unparse"
# @return [String] The quoted string
#
def self.quote(x)
escaped = '"'.dup
p = nil
x.each_char do |c|
case p
when nil
# do nothing
when "\t"
escaped << '\\t'
when "\n"
escaped << '\\n'
when "\f"
escaped << '\\f'
# TODO: \cx is a range of characters - skip for now
# when "\c"
# escaped << '\\c'
when '"'
escaped << '\\"'
when '\\'
escaped << ((c == '$' || c == 's') ? p : '\\\\') # don't escape \ when followed by s or $
else
escaped << p
end
p = c
end
escaped << p unless p.nil?
escaped << '"'
end
class EvaluatingEppParser < EvaluatingParser
def initialize
@parser = EppParser.new()
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/parser/interpolation_support.rb | lib/puppet/pops/parser/interpolation_support.rb | # frozen_string_literal: true
# This module is an integral part of the Lexer.
# It defines interpolation support
# PERFORMANCE NOTE: There are 4 very similar methods in this module that are designed to be as
# performant as possible. While it is possible to parameterize them into one common method, the overhead
# of passing parameters and evaluating conditional logic has a negative impact on performance.
#
module Puppet::Pops::Parser::InterpolationSupport
PATTERN_VARIABLE = /(::)?(\w+::)*\w+/
# This is the starting point for a double quoted string with possible interpolation
# The structure mimics that of the grammar.
# The logic is explicit (where the former implementation used parameters/structures) given to a
# generic handler.
# (This is both easier to understand and faster).
#
def interpolate_dq
scn = @scanner
ctx = @lexing_context
before = scn.pos
# skip the leading " by doing a scan since the slurp_dqstring uses last matched when there is an error
scn.scan(/"/)
value, terminator = slurp_dqstring()
text = value
after = scn.pos
loop do
case terminator
when '"'
# simple case, there was no interpolation, return directly
return emit_completed([:STRING, text, scn.pos - before], before)
when '${'
count = ctx[:brace_count]
ctx[:brace_count] += 1
# The ${ terminator is counted towards the string part
enqueue_completed([:DQPRE, text, scn.pos - before], before)
# Lex expression tokens until a closing (balanced) brace count is reached
enqueue_until count
break
when '$'
varname = scn.scan(PATTERN_VARIABLE)
if varname
# The $ is counted towards the variable
enqueue_completed([:DQPRE, text, after - before - 1], before)
enqueue_completed([:VARIABLE, varname, scn.pos - after + 1], after - 1)
break
else
# false $ variable start
text += terminator
value, terminator = slurp_dqstring()
text += value
after = scn.pos
end
end
end
interpolate_tail_dq
# return the first enqueued token and shift the queue
@token_queue.shift
end
def interpolate_tail_dq
scn = @scanner
ctx = @lexing_context
before = scn.pos
value, terminator = slurp_dqstring
text = value
after = scn.pos
loop do
case terminator
when '"'
# simple case, there was no further interpolation, return directly
enqueue_completed([:DQPOST, text, scn.pos - before], before)
return
when '${'
count = ctx[:brace_count]
ctx[:brace_count] += 1
# The ${ terminator is counted towards the string part
enqueue_completed([:DQMID, text, scn.pos - before], before)
# Lex expression tokens until a closing (balanced) brace count is reached
enqueue_until count
break
when '$'
varname = scn.scan(PATTERN_VARIABLE)
if varname
# The $ is counted towards the variable
enqueue_completed([:DQMID, text, after - before - 1], before)
enqueue_completed([:VARIABLE, varname, scn.pos - after + 1], after - 1)
break
else
# false $ variable start
text += terminator
value, terminator = slurp_dqstring
text += value
after = scn.pos
end
end
end
interpolate_tail_dq
end
# This is the starting point for a un-quoted string with possible interpolation
# The logic is explicit (where the former implementation used parameters/strucures) given to a
# generic handler.
# (This is both easier to understand and faster).
#
def interpolate_uq
scn = @scanner
ctx = @lexing_context
before = scn.pos
value, terminator = slurp_uqstring()
text = value
after = scn.pos
loop do
case terminator
when ''
# simple case, there was no interpolation, return directly
enqueue_completed([:STRING, text, scn.pos - before], before)
return
when '${'
count = ctx[:brace_count]
ctx[:brace_count] += 1
# The ${ terminator is counted towards the string part
enqueue_completed([:DQPRE, text, scn.pos - before], before)
# Lex expression tokens until a closing (balanced) brace count is reached
enqueue_until count
break
when '$'
varname = scn.scan(PATTERN_VARIABLE)
if varname
# The $ is counted towards the variable
enqueue_completed([:DQPRE, text, after - before - 1], before)
enqueue_completed([:VARIABLE, varname, scn.pos - after + 1], after - 1)
break
else
# false $ variable start
text += terminator
value, terminator = slurp_uqstring()
text += value
after = scn.pos
end
end
end
interpolate_tail_uq
nil
end
def interpolate_tail_uq
scn = @scanner
ctx = @lexing_context
before = scn.pos
value, terminator = slurp_uqstring
text = value
after = scn.pos
loop do
case terminator
when ''
# simple case, there was no further interpolation, return directly
enqueue_completed([:DQPOST, text, scn.pos - before], before)
return
when '${'
count = ctx[:brace_count]
ctx[:brace_count] += 1
# The ${ terminator is counted towards the string part
enqueue_completed([:DQMID, text, scn.pos - before], before)
# Lex expression tokens until a closing (balanced) brace count is reached
enqueue_until count
break
when '$'
varname = scn.scan(PATTERN_VARIABLE)
if varname
# The $ is counted towards the variable
enqueue_completed([:DQMID, text, after - before - 1], before)
enqueue_completed([:VARIABLE, varname, scn.pos - after + 1], after - 1)
break
else
# false $ variable start
text += terminator
value, terminator = slurp_uqstring
text += value
after = scn.pos
end
end
end
interpolate_tail_uq
end
# Enqueues lexed tokens until either end of input, or the given brace_count is reached
#
def enqueue_until brace_count
scn = @scanner
ctx = @lexing_context
queue = @token_queue
queue_base = @token_queue[0]
scn.skip(self.class::PATTERN_WS)
queue_size = queue.size
until scn.eos?
token = lex_token
if token
if token.equal?(queue_base)
# A nested #interpolate_dq call shifted the queue_base token from the @token_queue. It must
# be put back since it is intended for the top level #interpolate_dq call only.
queue.insert(0, token)
next # all relevant tokens are already on the queue
end
token_name = token[0]
ctx[:after] = token_name
if token_name == :RBRACE && ctx[:brace_count] == brace_count
qlength = queue.size - queue_size
if qlength == 1
# Single token is subject to replacement
queue[-1] = transform_to_variable(queue[-1])
elsif qlength > 1 && [:DOT, :LBRACK].include?(queue[queue_size + 1][0])
# A first word, number of name token followed by '[' or '.' is subject to replacement
# But not for other operators such as ?, +, - etc. where user must use a $ before the name
# to get a variable
queue[queue_size] = transform_to_variable(queue[queue_size])
end
return
end
queue << token
else
scn.skip(self.class::PATTERN_WS)
end
end
end
def transform_to_variable(token)
token_name = token[0]
if [:NUMBER, :NAME, :WORD].include?(token_name) || self.class::KEYWORD_NAMES[token_name] || @taskm_keywords[token_name]
t = token[1]
ta = t.token_array
[:VARIABLE, self.class::TokenValue.new([:VARIABLE, ta[1], ta[2]], t.offset, t.locator)]
else
token
end
end
# Interpolates unquoted string and transfers the result to the given lexer
# (This is used when a second lexer instance is used to lex a substring)
#
def interpolate_uq_to(lexer)
interpolate_uq
queue = @token_queue
until queue.empty?
lexer.enqueue(queue.shift)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/parser/locatable.rb | lib/puppet/pops/parser/locatable.rb | # frozen_string_literal: true
# Interface for something that is "locatable" (holds offset and length).
class Puppet::Pops::Parser::Locatable
# The offset in the locator's content
def offset
end
# The length in the locator from the given offset
def length
end
# This class is useful for testing
class Fixed < Puppet::Pops::Parser::Locatable
attr_reader :offset
attr_reader :length
def initialize(offset, length)
@offset = offset
@length = length
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/parser/pn_parser.rb | lib/puppet/pops/parser/pn_parser.rb | # frozen_string_literal: true
module Puppet::Pops
module Parser
class PNParser
LIT_TRUE = 'true'
LIT_FALSE = 'false'
LIT_NIL = 'nil'
TOKEN_END = 0
TOKEN_BOOL = 1
TOKEN_NIL = 2
TOKEN_INT = 3
TOKEN_FLOAT = 4
TOKEN_IDENTIFIER = 5
TOKEN_WS = 0x20
TOKEN_STRING = 0x22
TOKEN_KEY = 0x3a
TOKEN_LP = 0x28
TOKEN_RP = 0x29
TOKEN_LB = 0x5b
TOKEN_RB = 0x5d
TOKEN_LC = 0x7b
TOKEN_RC = 0x7d
TYPE_END = 0
TYPE_WS = 1
TYPE_DELIM = 2
TYPE_KEY_START = 3
TYPE_STRING_START = 4
TYPE_IDENTIFIER = 5
TYPE_MINUS = 6
TYPE_DIGIT = 7
TYPE_ALPHA = 8
def initialize
@char_types = self.class.char_types
end
def parse(text, locator = nil, offset = nil)
@locator = locator
@offset = offset
@text = text
@codepoints = text.codepoints.to_a.freeze
@pos = 0
@token = TOKEN_END
@token_value = nil
next_token
parse_next
end
def self.char_types
unless instance_variable_defined?(:@char_types)
@char_types = Array.new(0x80, TYPE_IDENTIFIER)
@char_types[0] = TYPE_END
[0x09, 0x0d, 0x0a, 0x20].each { |n| @char_types[n] = TYPE_WS }
[TOKEN_LP, TOKEN_RP, TOKEN_LB, TOKEN_RB, TOKEN_LC, TOKEN_RC].each { |n| @char_types[n] = TYPE_DELIM }
@char_types[0x2d] = TYPE_MINUS
(0x30..0x39).each { |n| @char_types[n] = TYPE_DIGIT }
(0x41..0x5a).each { |n| @char_types[n] = TYPE_ALPHA }
(0x61..0x7a).each { |n| @char_types[n] = TYPE_ALPHA }
@char_types[TOKEN_KEY] = TYPE_KEY_START
@char_types[TOKEN_STRING] = TYPE_STRING_START
@char_types.freeze
end
@char_types
end
private
def parse_next
case @token
when TOKEN_LB
parse_array
when TOKEN_LC
parse_map
when TOKEN_LP
parse_call
when TOKEN_BOOL, TOKEN_INT, TOKEN_FLOAT, TOKEN_STRING, TOKEN_NIL
parse_literal
when TOKEN_END
parse_error(_('unexpected end of input'))
else
parse_error(_('unexpected %{value}' % { value: @token_value }))
end
end
def parse_error(message)
file = ''
line = 1
pos = 1
if @locator
file = @locator.file
line = @locator.line_for_offset(@offset)
pos = @locator.pos_on_line(@offset)
end
@codepoints[0, @pos].each do |c|
if c == 0x09
line += 1
pos = 1
end
end
raise Puppet::ParseError.new(message, file, line, pos)
end
def parse_literal
pn = PN::Literal.new(@token_value)
next_token
pn
end
def parse_array
next_token
PN::List.new(parse_elements(TOKEN_RB))
end
def parse_map
next_token
entries = []
while @token != TOKEN_RC && @token != TOKEN_END
parse_error(_('map key expected')) unless @token == TOKEN_KEY
key = @token_value
next_token
entries << parse_next.with_name(key)
end
next_token
PN::Map.new(entries)
end
def parse_call
next_token
parse_error(_("expected identifier to follow '('")) unless @token == TOKEN_IDENTIFIER
name = @token_value
next_token
PN::Call.new(name, *parse_elements(TOKEN_RP))
end
def parse_elements(end_token)
elements = []
while @token != end_token && @token != TOKEN_END
elements << parse_next
end
parse_error(_("missing '%{token}' to end list") % { token: end_token.chr(Encoding::UTF_8) }) unless @token == end_token
next_token
elements
end
# All methods below belong to the PN lexer
def next_token
skip_white
s = @pos
c = next_cp
case @char_types[c]
when TYPE_END
@token_value = nil
@token = TOKEN_END
when TYPE_MINUS
if @char_types[peek_cp] == TYPE_DIGIT
next_token # consume float or integer
@token_value = -@token_value
else
consume_identifier(s)
end
when TYPE_DIGIT
skip_decimal_digits
c = peek_cp
if c == 0x2e # '.'
@pos += 1
consume_float(s, c)
else
@token_value = @text[s..@pos].to_i
@token = TOKEN_INT
end
when TYPE_DELIM
@token_value = @text[s]
@token = c
when TYPE_KEY_START
if @char_types[peek_cp] == TYPE_ALPHA
next_token
@token = TOKEN_KEY
else
parse_error(_("expected identifier after ':'"))
end
when TYPE_STRING_START
consume_string
else
consume_identifier(s)
end
end
def consume_identifier(s)
while @char_types[peek_cp] >= TYPE_IDENTIFIER
@pos += 1
end
id = @text[s...@pos]
case id
when LIT_TRUE
@token = TOKEN_BOOL
@token_value = true
when LIT_FALSE
@token = TOKEN_BOOL
@token_value = false
when LIT_NIL
@token = TOKEN_NIL
@token_value = nil
else
@token = TOKEN_IDENTIFIER
@token_value = id
end
end
def consume_string
s = @pos
b = ''.dup
loop do
c = next_cp
case c
when TOKEN_END
@pos = s - 1
parse_error(_('unterminated quote'))
when TOKEN_STRING
@token_value = b
@token = TOKEN_STRING
break
when 0x5c # '\'
c = next_cp
case c
when 0x74 # 't'
b << "\t"
when 0x72 # 'r'
b << "\r"
when 0x6e # 'n'
b << "\n"
when TOKEN_STRING
b << '"'
when 0x5c # '\'
b << "\\"
when 0x6f # 'o'
c = 0
3.times do
n = next_cp
if 0x30 <= n && n <= 0x37c
c *= 8
c += n - 0x30
else
parse_error(_('malformed octal quote'))
end
end
b << c
else
b << "\\"
b << c
end
else
b << c
end
end
end
def consume_float(s, d)
parse_error(_('digit expected')) if skip_decimal_digits == 0
c = peek_cp
if d == 0x2e # '.'
if c == 0x45 || c == 0x65 # 'E' or 'e'
@pos += 1
parse_error(_('digit expected')) if skip_decimal_digits == 0
c = peek_cp
end
end
parse_error(_('digit expected')) if @char_types[c] == TYPE_ALPHA
@token_value = @text[s...@pos].to_f
@token = TOKEN_FLOAT
end
def skip_decimal_digits
count = 0
c = peek_cp
if c == 0x2d || c == 0x2b # '-' or '+'
@pos += 1
c = peek_cp
end
while @char_types[c] == TYPE_DIGIT
@pos += 1
c = peek_cp
count += 1
end
count
end
def skip_white
while @char_types[peek_cp] == TYPE_WS
@pos += 1
end
end
def next_cp
c = 0
if @pos < @codepoints.size
c = @codepoints[@pos]
@pos += 1
end
c
end
def peek_cp
@pos < @codepoints.size ? @codepoints[@pos] : 0
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/parser/lexer_support.rb | lib/puppet/pops/parser/lexer_support.rb | # frozen_string_literal: true
module Puppet::Pops
module Parser
require_relative '../../../puppet/util/multi_match'
# This is an integral part of the Lexer. It is broken out into a separate module
# for maintainability of the code, and making the various parts of the lexer focused.
#
module LexerSupport
# Returns "<eof>" if at end of input, else the following 5 characters with \n \r \t escaped
def followed_by
return "<eof>" if @scanner.eos?
result = @scanner.rest[0, 5] + "..."
result.gsub!("\t", '\t')
result.gsub!("\n", '\n')
result.gsub!("\r", '\r')
result
end
# Returns a quoted string using " or ' depending on the given a strings's content
def format_quote(q)
if q == "'"
'"\'"'
else
"'#{q}'"
end
end
# Raises a Puppet::LexError with the given message
def lex_error_without_pos(issue, args = {})
raise Puppet::ParseErrorWithIssue.new(issue.format(args), nil, nil, nil, nil, issue.issue_code, args)
end
# Raises a Puppet::ParserErrorWithIssue with the given issue and arguments
def lex_error(issue, args = {}, pos = nil)
raise create_lex_error(issue, args, pos)
end
def filename
file = @locator.file
file.is_a?(String) && !file.empty? ? file : nil
end
def line(pos)
@locator.line_for_offset(pos || @scanner.pos)
end
def position(pos)
@locator.pos_on_line(pos || @scanner.pos)
end
def lex_warning(issue, args = {}, pos = nil)
Puppet::Util::Log.create({
:level => :warning,
:message => issue.format(args),
:issue_code => issue.issue_code,
:file => filename,
:line => line(pos),
:pos => position(pos),
})
end
# @param issue [Issues::Issue] the issue
# @param args [Hash<Symbol,String>] Issue arguments
# @param pos [Integer]
# @return [Puppet::ParseErrorWithIssue] the created error
def create_lex_error(issue, args = {}, pos = nil)
Puppet::ParseErrorWithIssue.new(
issue.format(args),
filename,
line(pos),
position(pos),
nil,
issue.issue_code,
args
)
end
# Asserts that the given string value is a float, or an integer in decimal, octal or hex form.
# An error is raised if the given value does not comply.
#
def assert_numeric(value, pos)
case value
when /^0[xX]/
lex_error(Issues::INVALID_HEX_NUMBER, { :value => value }, pos) unless value =~ /^0[xX][0-9A-Fa-f]+$/
when /^0[^.]/
lex_error(Issues::INVALID_OCTAL_NUMBER, { :value => value }, pos) unless value =~ /^0[0-7]+$/
when /^\d+[eE.]/
lex_error(Issues::INVALID_DECIMAL_NUMBER, { :value => value }, pos) unless value =~ /^\d+(?:\.\d+)?(?:[eE]-?\d+)?$/
else
lex_error(Issues::ILLEGAL_NUMBER, { :value => value }, pos) unless value =~ /^\d+$/
end
end
# A TokenValue keeps track of the token symbol, the lexed text for the token, its length
# and its position in its source container. There is a cost associated with computing the
# line and position on line information.
#
class TokenValue < Locatable
attr_reader :token_array
attr_reader :offset
attr_reader :locator
def initialize(token_array, offset, locator)
@token_array = token_array
@offset = offset
@locator = locator
end
def length
@token_array[2]
end
def [](key)
case key
when :value
@token_array[1]
when :file
@locator.file
when :line
@locator.line_for_offset(@offset)
when :pos
@locator.pos_on_line(@offset)
when :length
@token_array[2]
when :locator
@locator
when :offset
@offset
else
nil
end
end
def to_s
# This format is very compact and is intended for debugging output from racc parser in
# debug mode. If this is made more elaborate the output from a debug run becomes very hard to read.
#
"'#{self[:value]} #{@token_array[0]}'"
end
# TODO: Make this comparable for testing
# vs symbolic, vs array with symbol and non hash, array with symbol and hash)
#
end
MM = Puppet::Util::MultiMatch
MM_ANY = MM::NOT_NIL
BOM_UTF_8 = MM.new(0xEF, 0xBB, 0xBF, MM_ANY)
BOM_UTF_16_1 = MM.new(0xFE, 0xFF, MM_ANY, MM_ANY)
BOM_UTF_16_2 = MM.new(0xFF, 0xFE, MM_ANY, MM_ANY)
BOM_UTF_32_1 = MM.new(0x00, 0x00, 0xFE, 0xFF)
BOM_UTF_32_2 = MM.new(0xFF, 0xFE, 0x00, 0x00)
BOM_UTF_1 = MM.new(0xF7, 0x64, 0x4C, MM_ANY)
BOM_UTF_EBCDIC = MM.new(0xDD, 0x73, 0x66, 0x73)
BOM_SCSU = MM.new(0x0E, 0xFE, 0xFF, MM_ANY)
BOM_BOCU = MM.new(0xFB, 0xEE, 0x28, MM_ANY)
BOM_GB_18030 = MM.new(0x84, 0x31, 0x95, 0x33)
LONGEST_BOM = 4
def assert_not_bom(content)
name, size =
case bom = get_bom(content)
when BOM_UTF_32_1, BOM_UTF_32_2
['UTF-32', 4]
when BOM_GB_18030
['GB-18030', 4]
when BOM_UTF_EBCDIC
['UTF-EBCDIC', 4]
when BOM_SCSU
['SCSU', 3]
when BOM_UTF_8
['UTF-8', 3]
when BOM_UTF_1
['UTF-1', 3]
when BOM_BOCU
['BOCU', 3]
when BOM_UTF_16_1, BOM_UTF_16_2
['UTF-16', 2]
else
return
end
lex_error_without_pos(
Puppet::Pops::Issues::ILLEGAL_BOM,
{ :format_name => name,
:bytes => "[#{bom.values[0, size].map { |b| '%X' % b }.join(' ')}]" }
)
end
def get_bom(content)
# get 5 bytes as efficiently as possible (none of the string methods works since a bom consists of
# illegal characters on most platforms, and there is no get_bytes(n). Explicit calls are faster than
# looping with a lambda. The get_byte returns nil if there are too few characters, and they
# are changed to spaces
MM.new(
(content.getbyte(0) || ' '),
(content.getbyte(1) || ' '),
(content.getbyte(2) || ' '),
(content.getbyte(3) || ' ')
)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/parser/epp_support.rb | lib/puppet/pops/parser/epp_support.rb | # frozen_string_literal: true
module Puppet::Pops
module Parser
# This module is an integral part of the Lexer.
# It handles scanning of EPP (Embedded Puppet), a form of string/expression interpolation similar to ERB.
#
require 'strscan'
module EppSupport
TOKEN_RENDER_STRING = [:RENDER_STRING, nil, 0]
TOKEN_RENDER_EXPR = [:RENDER_EXPR, nil, 0]
# Scans all of the content and returns it in an array
# Note that the terminating [false, false] token is included in the result.
#
def fullscan_epp
result = []
scan_epp { |token, value| result.push([token, value]) }
result
end
# A block must be passed to scan. It will be called with two arguments, a symbol for the token,
# and an instance of LexerSupport::TokenValue
# PERFORMANCE NOTE: The TokenValue is designed to reduce the amount of garbage / temporary data
# and to only convert the lexer's internal tokens on demand. It is slightly more costly to create an
# instance of a class defined in Ruby than an Array or Hash, but the gain is much bigger since transformation
# logic is avoided for many of its members (most are never used (e.g. line/pos information which is only of
# value in general for error messages, and for some expressions (which the lexer does not know about).
#
def scan_epp
# PERFORMANCE note: it is faster to access local variables than instance variables.
# This makes a small but notable difference since instance member access is avoided for
# every token in the lexed content.
#
scn = @scanner
ctx = @lexing_context
queue = @token_queue
lex_error(Issues::EPP_INTERNAL_ERROR, :error => 'No string or file given to lexer to process.') unless scn
ctx[:epp_mode] = :text
enqueue_completed([:EPP_START, nil, 0], 0)
interpolate_epp
# This is the lexer's main loop
until queue.empty? && scn.eos?
token = queue.shift || lex_token
if token
yield [ctx[:after] = token[0], token[1]]
end
end
if ctx[:epp_open_position]
lex_error(Issues::EPP_UNBALANCED_TAG, {}, ctx[:epp_position])
end
# Signals end of input
yield [false, false]
end
def interpolate_epp(skip_leading = false)
scn = @scanner
ctx = @lexing_context
eppscanner = EppScanner.new(scn)
before = scn.pos
s = eppscanner.scan(skip_leading)
case eppscanner.mode
when :text
# Should be at end of scan, or something is terribly wrong
unless @scanner.eos?
lex_error(Issues::EPP_INTERNAL_ERROR, :error => 'template scanner returns text mode and is not and end of input')
end
if s
# s may be nil if scanned text ends with an epp tag (i.e. no trailing text).
enqueue_completed([:RENDER_STRING, s, scn.pos - before], before)
end
ctx[:epp_open_position] = nil
# do nothing else, scanner is at the end
when :error
lex_error(eppscanner.issue)
when :epp
# It is meaningless to render empty string segments, and it is harmful to do this at
# the start of the scan as it prevents specification of parameters with <%- ($x, $y) -%>
#
if s && s.length > 0
enqueue_completed([:RENDER_STRING, s, scn.pos - before], before)
end
# switch epp_mode to general (embedded) pp logic (non rendered result)
ctx[:epp_mode] = :epp
ctx[:epp_open_position] = scn.pos
when :expr
# It is meaningless to render an empty string segment
if s && s.length > 0
enqueue_completed([:RENDER_STRING, s, scn.pos - before], before)
end
enqueue_completed(TOKEN_RENDER_EXPR, before)
# switch mode to "epp expr interpolation"
ctx[:epp_mode] = :expr
ctx[:epp_open_position] = scn.pos
else
lex_error(Issues::EPP_INTERNAL_ERROR, :error => "Unknown mode #{eppscanner.mode} returned by template scanner")
end
nil
end
# A scanner specialized in processing text with embedded EPP (Embedded Puppet) tags.
# The scanner is initialized with a StringScanner which it mutates as scanning takes place.
# The intent is to use one instance of EppScanner per wanted scan, and this instance represents
# the state after the scan.
#
# @example Sample usage
# a = "some text <% pp code %> some more text"
# scan = StringScanner.new(a)
# eppscan = EppScanner.new(scan)
# str = eppscan.scan
# eppscan.mode # => :epp
# eppscan.lines # => 0
# eppscan
#
# The scanner supports
# * scanning text until <%, <%-, <%=
# * while scanning text:
# * tokens <%% and %%> are translated to <% and %>, respectively, and is returned as text.
# * tokens <%# and %> (or ending with -%>) and the enclosed text is a comment and is not included in the returned text
# * text following a comment that ends with -%> gets trailing whitespace (up to and including a line break) trimmed
# and this whitespace is not included in the returned text.
# * The continuation {#mode} is set to one of:
# * `:epp` - for a <% token
# * `:expr` - for a <%= token
# * `:text` - when there was no continuation mode (e.g. when input ends with text)
# * ':error` - if the tokens are unbalanced (reaching the end without a closing matching token). An error message
# is then also available via the method {#message}.
#
# Note that the intent is to use this specialized scanner to scan the text parts, when continuation mode is `:epp` or `:expr`
# the pp lexer should advance scanning (using the string scanner) until it reaches and consumes a `-%>` or '%>´ token. If it
# finds a `-%> token it should pass this on as a `skip_leading` parameter when it performs the next {#scan}.
#
class EppScanner
# The original scanner used by the lexer/container using EppScanner
attr_reader :scanner
# The resulting mode after the scan.
# The mode is one of `:text` (the initial mode), `:epp` embedded code (no output), `:expr` (embedded
# expression), or `:error`
#
attr_reader :mode
# An error issue if `mode == :error`, `nil` otherwise.
attr_reader :issue
# If the first scan should skip leading whitespace (typically detected by the pp lexer when the
# pp mode end-token is found (i.e. `-%>`) and then passed on to the scanner.
#
attr_reader :skip_leading
# Creates an EppScanner based on a StringScanner that represents the state where EppScanner should start scanning.
# The given scanner will be mutated (i.e. position moved) to reflect the EppScanner's end state after a scan.
#
def initialize(scanner)
@scanner = scanner
end
# Here for backwards compatibility.
# @deprecated Use issue instead
# @return [String] the issue message
def message
@issue.nil? ? nil : @issue.format
end
# Scans from the current position in the configured scanner, advances this scanner's position until the end
# of the input, or to the first position after a mode switching token (`<%`, `<%-` or `<%=`). Number of processed
# lines and continuation mode can be obtained via {#lines}, and {#mode}.
#
# @return [String, nil] the scanned and processed text, or nil if at the end of the input.
#
def scan(skip_leading = false)
@mode = :text
@skip_leading = skip_leading
return nil if scanner.eos?
s = ''.dup
until scanner.eos?
part = @scanner.scan_until(/(<%)|\z/)
if @skip_leading
part.sub!(/^[ \t]*\r?(?:\n|\z)?/, '')
@skip_leading = false
end
# The spec for %%> is to transform it into a literal %>. This is done here, as %%> otherwise would go
# undetected in text mode. (i.e. it is not really necessary to escape %> with %%> in text mode unless
# adding checks stating that a literal %> is illegal in text (unbalanced).
#
part.gsub!(/%%>/, '%>')
s += part
case @scanner.peek(1)
when ""
# at the end
# if s ends with <% then this is an error (unbalanced <% %>)
if s.end_with? "<%"
@mode = :error
@issue = Issues::EPP_UNBALANCED_EXPRESSION
end
return s
when "-"
# trim trailing whitespace on same line from accumulated s
# return text and signal switch to pp mode
@scanner.getch # drop the -
s.sub!(/[ \t]*<%\z/, '')
@mode = :epp
return s
when "%"
# verbatim text
# keep the scanned <%, and continue scanning after skipping one %
# (i.e. do nothing here)
@scanner.getch # drop the % to get a literal <% in the output
when "="
# expression
# return text and signal switch to expression mode
# drop the scanned <%, and skip past -%>, or %>, but also skip %%>
@scanner.getch # drop the =
s.slice!(-2..-1)
@mode = :expr
return s
when "#"
# template comment
# drop the scanned <%, and skip past -%>, or %>, but also skip %%>
s.slice!(-2..-1)
# unless there is an immediate termination i.e. <%#%> scan for the next %> that is not
# preceded by a % (i.e. skip %%>)
part = scanner.scan_until(/[^%]%>/)
unless part
@issue = Issues::EPP_UNBALANCED_COMMENT
@mode = :error
return s
end
# Trim leading whitespace on the same line when start was <%#-
if part[1] == '-'
s.sub!(/[ \t]*\z/, '')
end
@skip_leading = true if part.end_with?("-%>")
# Continue scanning for more text
else
# Switch to pp after having removed the <%
s.slice!(-2..-1)
@mode = :epp
return s
end
end
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/parser/epp_parser.rb | lib/puppet/pops/parser/epp_parser.rb | # frozen_string_literal: true
# The EppParser is a specialized Puppet Parser that starts parsing in Epp Text mode
class Puppet::Pops::Parser::EppParser < Puppet::Pops::Parser::Parser
# Initializes the epp parser support by creating a new instance of {Puppet::Pops::Parser::Lexer}
# configured to start in Epp Lexing mode.
# @return [void]
#
def initvars
self.lexer = Puppet::Pops::Parser::Lexer2.new()
end
# Parses a file expected to contain epp text/DSL logic.
def parse_file(file)
unless FileTest.exist?(file)
unless file =~ /\.epp$/
file += ".epp"
end
end
@lexer.file = file
_parse()
end
# Performs the parsing and returns the resulting model.
# The lexer holds state, and this is setup with {#parse_string}, or {#parse_file}.
#
# TODO: deal with options containing origin (i.e. parsing a string from externally known location).
# TODO: should return the model, not a Hostclass
#
# @api private
#
def _parse
begin
@yydebug = false
main = yyparse(@lexer, :scan_epp)
# #Commented out now because this hides problems in the racc grammar while developing
# # TODO include this when test coverage is good enough.
# rescue Puppet::ParseError => except
# except.line ||= @lexer.line
# except.file ||= @lexer.file
# except.pos ||= @lexer.pos
# raise except
# rescue => except
# raise Puppet::ParseError.new(except.message, @lexer.file, @lexer.line, @lexer.pos, except)
end
main
ensure
@lexer.clear
@namestack = []
@definitions = []
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/parser/heredoc_support.rb | lib/puppet/pops/parser/heredoc_support.rb | # frozen_string_literal: true
module Puppet::Pops
module Parser
module HeredocSupport
include LexerSupport
# Pattern for heredoc `@(endtag[:syntax][/escapes])
# Produces groups for endtag (group 1), syntax (group 2), and escapes (group 3)
#
PATTERN_HEREDOC = %r{@\(([^:/\r\n)]+)(?::[[:blank:]]*([a-z][a-zA-Z0-9_+]+)[[:blank:]]*)?(?:/((?:\w|[$])*)[[:blank:]]*)?\)}
def heredoc
scn = @scanner
ctx = @lexing_context
locator = @locator
before = scn.pos
# scanner is at position before @(
# find end of the heredoc spec
str = scn.scan_until(/\)/) || lex_error(Issues::HEREDOC_UNCLOSED_PARENTHESIS, :followed_by => followed_by)
pos_after_heredoc = scn.pos
# Note: allows '+' as separator in syntax, but this needs validation as empty segments are not allowed
md = str.match(PATTERN_HEREDOC)
lex_error(Issues::HEREDOC_INVALID_SYNTAX) unless md
endtag = md[1]
syntax = md[2] || ''
escapes = md[3]
endtag.strip!
# Is this a dq string style heredoc? (endtag enclosed in "")
if endtag =~ /^"(.*)"$/
dqstring_style = true
endtag = ::Regexp.last_match(1).strip
end
lex_error(Issues::HEREDOC_EMPTY_ENDTAG) unless endtag.length >= 1
resulting_escapes = []
if escapes
escapes = "trnsuL$" if escapes.length < 1
escapes = escapes.split('')
unless escapes.length == escapes.uniq.length
lex_error(Issues::HEREDOC_MULTIPLE_AT_ESCAPES, :escapes => escapes)
end
resulting_escapes = ["\\"]
escapes.each do |e|
case e
when "t", "r", "n", "s", "u", "$"
resulting_escapes << e
when "L"
resulting_escapes += ["\n", "\r\n"]
else
lex_error(Issues::HEREDOC_INVALID_ESCAPE, :actual => e)
end
end
end
# Produce a heredoc token to make the syntax available to the grammar
enqueue_completed([:HEREDOC, syntax, pos_after_heredoc - before], before)
# If this is the second or subsequent heredoc on the line, the lexing context's :newline_jump contains
# the position after the \n where the next heredoc text should scan. If not set, this is the first
# and it should start scanning after the first found \n (or if not found == error).
if ctx[:newline_jump]
scn.pos = ctx[:newline_jump]
else
scn.scan_until(/\n/) || lex_error(Issues::HEREDOC_WITHOUT_TEXT)
end
# offset 0 for the heredoc, and its line number
heredoc_offset = scn.pos
heredoc_line = locator.line_for_offset(heredoc_offset) - 1
# Compute message to emit if there is no end (to make it refer to the opening heredoc position).
eof_error = create_lex_error(Issues::HEREDOC_WITHOUT_END_TAGGED_LINE)
# Text from this position (+ lexing contexts offset for any preceding heredoc) is heredoc until a line
# that terminates the heredoc is found.
# (Endline in EBNF form): WS* ('|' WS*)? ('-' WS*)? endtag WS* \r? (\n|$)
endline_pattern = /([[:blank:]]*)(?:([|])[[:blank:]]*)?(?:(-)[[:blank:]]*)?#{Regexp.escape(endtag)}[[:blank:]]*\r?(?:\n|\z)/
lines = []
until scn.eos?
one_line = scn.scan_until(/(?:\n|\z)/)
raise eof_error unless one_line
md = one_line.match(endline_pattern)
if md
leading = md[1]
has_margin = md[2] == '|'
remove_break = md[3] == '-'
# Record position where next heredoc (from same line as current @()) should start scanning for content
ctx[:newline_jump] = scn.pos
# Process captured lines - remove leading, and trailing newline
# get processed string and index of removed margin/leading size per line
str, margin_per_line = heredoc_text(lines, leading, has_margin, remove_break)
# Use a new lexer instance configured with a sub-locator to enable correct positioning
sublexer = self.class.new()
locator = Locator::SubLocator.new(locator, str, heredoc_line, heredoc_offset, has_margin, margin_per_line)
# Emit a token that provides the grammar with location information about the lines on which the heredoc
# content is based.
enqueue([:SUBLOCATE,
LexerSupport::TokenValue.new([:SUBLOCATE,
lines, lines.reduce(0) { |size, s| size + s.length }],
heredoc_offset,
locator)])
sublexer.lex_unquoted_string(str, locator, resulting_escapes, dqstring_style)
sublexer.interpolate_uq_to(self)
# Continue scan after @(...)
scn.pos = pos_after_heredoc
return
else
lines << one_line
end
end
raise eof_error
end
# Produces the heredoc text string given the individual (unprocessed) lines as an array and array with margin sizes per line
# @param lines [Array<String>] unprocessed lines of text in the heredoc w/o terminating line
# @param leading [String] the leading text up (up to pipe or other terminating char)
# @param has_margin [Boolean] if the left margin should be adjusted as indicated by `leading`
# @param remove_break [Boolean] if the line break (\r?\n) at the end of the last line should be removed or not
# @return [Array] - a tuple with resulting string, and an array with margin size per line
#
def heredoc_text(lines, leading, has_margin, remove_break)
if has_margin && leading.length > 0
leading_pattern = /^#{Regexp.escape(leading)}/
# TODO: This implementation is not according to the specification, but is kept to be bug compatible.
# The specification says that leading space up to the margin marker should be removed, but this implementation
# simply leaves lines that have text in the margin untouched.
#
processed_lines = lines.collect { |s| s.gsub(leading_pattern, '') }
margin_per_line = Array.new(processed_lines.length) { |x| lines[x].length - processed_lines[x].length }
lines = processed_lines
else
# Array with a 0 per line
margin_per_line = Array.new(lines.length, 0)
end
result = lines.join('')
result.gsub!(/\r?\n\z/m, '') if remove_break
[result, margin_per_line]
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/parser/lexer2.rb | lib/puppet/pops/parser/lexer2.rb | # frozen_string_literal: true
# The Lexer is responsible for turning source text into tokens.
# This version is a performance enhanced lexer (in comparison to the 3.x and earlier "future parser" lexer.
#
# Old returns tokens [:KEY, value, { locator = }
# Could return [[token], locator]
# or Token.new([token], locator) with the same API x[0] = token_symbol, x[1] = self, x[:key] = (:value, :file, :line, :pos) etc
require 'strscan'
require_relative '../../../puppet/pops/parser/lexer_support'
require_relative '../../../puppet/pops/parser/heredoc_support'
require_relative '../../../puppet/pops/parser/interpolation_support'
require_relative '../../../puppet/pops/parser/epp_support'
require_relative '../../../puppet/pops/parser/slurp_support'
module Puppet::Pops
module Parser
class Lexer2
include LexerSupport
include HeredocSupport
include InterpolationSupport
include SlurpSupport
include EppSupport
# ALl tokens have three slots, the token name (a Symbol), the token text (String), and a token text length.
# All operator and punctuation tokens reuse singleton arrays Tokens that require unique values create
# a unique array per token.
#
# PEFORMANCE NOTES:
# This construct reduces the amount of object that needs to be created for operators and punctuation.
# The length is pre-calculated for all singleton tokens. The length is used both to signal the length of
# the token, and to advance the scanner position (without having to advance it with a scan(regexp)).
#
TOKEN_LBRACK = [:LBRACK, '[', 1].freeze
TOKEN_LISTSTART = [:LISTSTART, '[', 1].freeze
TOKEN_RBRACK = [:RBRACK, ']', 1].freeze
TOKEN_LBRACE = [:LBRACE, '{', 1].freeze
TOKEN_RBRACE = [:RBRACE, '}', 1].freeze
TOKEN_SELBRACE = [:SELBRACE, '{', 1].freeze
TOKEN_LPAREN = [:LPAREN, '(', 1].freeze
TOKEN_WSLPAREN = [:WSLPAREN, '(', 1].freeze
TOKEN_RPAREN = [:RPAREN, ')', 1].freeze
TOKEN_EQUALS = [:EQUALS, '=', 1].freeze
TOKEN_APPENDS = [:APPENDS, '+=', 2].freeze
TOKEN_DELETES = [:DELETES, '-=', 2].freeze
TOKEN_ISEQUAL = [:ISEQUAL, '==', 2].freeze
TOKEN_NOTEQUAL = [:NOTEQUAL, '!=', 2].freeze
TOKEN_MATCH = [:MATCH, '=~', 2].freeze
TOKEN_NOMATCH = [:NOMATCH, '!~', 2].freeze
TOKEN_GREATEREQUAL = [:GREATEREQUAL, '>=', 2].freeze
TOKEN_GREATERTHAN = [:GREATERTHAN, '>', 1].freeze
TOKEN_LESSEQUAL = [:LESSEQUAL, '<=', 2].freeze
TOKEN_LESSTHAN = [:LESSTHAN, '<', 1].freeze
TOKEN_FARROW = [:FARROW, '=>', 2].freeze
TOKEN_PARROW = [:PARROW, '+>', 2].freeze
TOKEN_LSHIFT = [:LSHIFT, '<<', 2].freeze
TOKEN_LLCOLLECT = [:LLCOLLECT, '<<|', 3].freeze
TOKEN_LCOLLECT = [:LCOLLECT, '<|', 2].freeze
TOKEN_RSHIFT = [:RSHIFT, '>>', 2].freeze
TOKEN_RRCOLLECT = [:RRCOLLECT, '|>>', 3].freeze
TOKEN_RCOLLECT = [:RCOLLECT, '|>', 2].freeze
TOKEN_PLUS = [:PLUS, '+', 1].freeze
TOKEN_MINUS = [:MINUS, '-', 1].freeze
TOKEN_DIV = [:DIV, '/', 1].freeze
TOKEN_TIMES = [:TIMES, '*', 1].freeze
TOKEN_MODULO = [:MODULO, '%', 1].freeze
# rubocop:disable Layout/SpaceBeforeComma
TOKEN_NOT = [:NOT, '!', 1].freeze
TOKEN_DOT = [:DOT, '.', 1].freeze
TOKEN_PIPE = [:PIPE, '|', 1].freeze
TOKEN_AT = [:AT , '@', 1].freeze
TOKEN_ATAT = [:ATAT , '@@', 2].freeze
TOKEN_COLON = [:COLON, ':', 1].freeze
TOKEN_COMMA = [:COMMA, ',', 1].freeze
TOKEN_SEMIC = [:SEMIC, ';', 1].freeze
TOKEN_QMARK = [:QMARK, '?', 1].freeze
TOKEN_TILDE = [:TILDE, '~', 1].freeze # lexed but not an operator in Puppet
# rubocop:enable Layout/SpaceBeforeComma
TOKEN_REGEXP = [:REGEXP, nil, 0].freeze
TOKEN_IN_EDGE = [:IN_EDGE, '->', 2].freeze
TOKEN_IN_EDGE_SUB = [:IN_EDGE_SUB, '~>', 2].freeze
TOKEN_OUT_EDGE = [:OUT_EDGE, '<-', 2].freeze
TOKEN_OUT_EDGE_SUB = [:OUT_EDGE_SUB, '<~', 2].freeze
# Tokens that are always unique to what has been lexed
TOKEN_STRING = [:STRING, nil, 0].freeze
TOKEN_WORD = [:WORD, nil, 0].freeze
TOKEN_DQPRE = [:DQPRE, nil, 0].freeze
TOKEN_DQMID = [:DQPRE, nil, 0].freeze
TOKEN_DQPOS = [:DQPRE, nil, 0].freeze
TOKEN_NUMBER = [:NUMBER, nil, 0].freeze
TOKEN_VARIABLE = [:VARIABLE, nil, 1].freeze
TOKEN_VARIABLE_EMPTY = [:VARIABLE, '', 1].freeze
# HEREDOC has syntax as an argument.
TOKEN_HEREDOC = [:HEREDOC, nil, 0].freeze
# EPP_START is currently a marker token, may later get syntax
# rubocop:disable Layout/ExtraSpacing
TOKEN_EPPSTART = [:EPP_START, nil, 0].freeze
TOKEN_EPPEND = [:EPP_END, '%>', 2].freeze
TOKEN_EPPEND_TRIM = [:EPP_END_TRIM, '-%>', 3].freeze
# rubocop:enable Layout/ExtraSpacing
# This is used for unrecognized tokens, will always be a single character. This particular instance
# is not used, but is kept here for documentation purposes.
TOKEN_OTHER = [:OTHER, nil, 0]
# Keywords are all singleton tokens with pre calculated lengths.
# Booleans are pre-calculated (rather than evaluating the strings "false" "true" repeatedly.
#
KEYWORDS = {
'case' => [:CASE, 'case', 4],
'class' => [:CLASS, 'class', 5],
'default' => [:DEFAULT, 'default', 7],
'define' => [:DEFINE, 'define', 6],
'if' => [:IF, 'if', 2],
'elsif' => [:ELSIF, 'elsif', 5],
'else' => [:ELSE, 'else', 4],
'inherits' => [:INHERITS, 'inherits', 8],
'node' => [:NODE, 'node', 4],
'and' => [:AND, 'and', 3],
'or' => [:OR, 'or', 2],
'undef' => [:UNDEF, 'undef', 5],
'false' => [:BOOLEAN, false, 5],
'true' => [:BOOLEAN, true, 4],
'in' => [:IN, 'in', 2],
'unless' => [:UNLESS, 'unless', 6],
'function' => [:FUNCTION, 'function', 8],
'type' => [:TYPE, 'type', 4],
'attr' => [:ATTR, 'attr', 4],
'private' => [:PRIVATE, 'private', 7],
}
KEYWORDS.each { |_k, v| v[1].freeze; v.freeze }
KEYWORDS.freeze
# Reverse lookup of keyword name to string
KEYWORD_NAMES = {}
KEYWORDS.each { |k, v| KEYWORD_NAMES[v[0]] = k }
KEYWORD_NAMES.freeze
PATTERN_WS = /[[:blank:]\r]+/
PATTERN_NON_WS = /\w+\b?/
# The single line comment includes the line ending.
PATTERN_COMMENT = /#.*\r?/
PATTERN_MLCOMMENT = %r{/\*(.*?)\*/}m
PATTERN_REGEX = %r{/[^/]*/}
PATTERN_REGEX_END = %r{/}
PATTERN_REGEX_A = %r{\A/} # for replacement to ""
PATTERN_REGEX_Z = %r{/\Z} # for replacement to ""
PATTERN_REGEX_ESC = %r{\\/} # for replacement to "/"
# The 3x patterns:
# PATTERN_CLASSREF = %r{((::){0,1}[A-Z][-\w]*)+}
# PATTERN_NAME = %r{((::)?[a-z0-9][-\w]*)(::[a-z0-9][-\w]*)*}
# The NAME and CLASSREF in 4x are strict. Each segment must start with
# a letter a-z and may not contain dashes (\w includes letters, digits and _).
#
PATTERN_CLASSREF = /((::){0,1}[A-Z]\w*)+/
PATTERN_NAME = /^((::)?[a-z]\w*)(::[a-z]\w*)*$/
PATTERN_BARE_WORD = /((?:::){0,1}(?:[a-z_](?:[\w-]*\w)?))+/
PATTERN_DOLLAR_VAR = /\$(::)?(\w+::)*\w+/
PATTERN_NUMBER = /\b(?:0[xX][0-9A-Fa-f]+|0?\d+(?:\.\d+)?(?:[eE]-?\d+)?)\b/
# PERFORMANCE NOTE:
# Comparison against a frozen string is faster (than unfrozen).
#
STRING_BSLASH_SLASH = '\/'
attr_reader :locator
def initialize
@selector = {
'.' => -> { emit(TOKEN_DOT, @scanner.pos) },
',' => -> { emit(TOKEN_COMMA, @scanner.pos) },
'[' => lambda do
before = @scanner.pos
# Must check the preceding character to see if it is whitespace.
# The fastest thing to do is to simply byteslice to get the string ending at the offset before
# and then check what the last character is. (This is the same as what an locator.char_offset needs
# to compute, but with less overhead of trying to find out the global offset from a local offset in the
# case when this is sublocated in a heredoc).
if before == 0 || @scanner.string.byteslice(0, before)[-1] =~ /[[:blank:]\r\n]+/
emit(TOKEN_LISTSTART, before)
else
emit(TOKEN_LBRACK, before)
end
end,
']' => -> { emit(TOKEN_RBRACK, @scanner.pos) },
'(' => lambda do
before = @scanner.pos
# If first on a line, or only whitespace between start of line and '('
# then the token is special to avoid being taken as start of a call.
line_start = @lexing_context[:line_lexical_start]
if before == line_start || @scanner.string.byteslice(line_start, before - line_start) =~ /\A[[:blank:]\r]+\Z/
emit(TOKEN_WSLPAREN, before)
else
emit(TOKEN_LPAREN, before)
end
end,
')' => -> { emit(TOKEN_RPAREN, @scanner.pos) },
';' => -> { emit(TOKEN_SEMIC, @scanner.pos) },
'?' => -> { emit(TOKEN_QMARK, @scanner.pos) },
'*' => -> { emit(TOKEN_TIMES, @scanner.pos) },
'%' => lambda do
scn = @scanner
before = scn.pos
la = scn.peek(2)
if la[1] == '>' && @lexing_context[:epp_mode]
scn.pos += 2
if @lexing_context[:epp_mode] == :expr
enqueue_completed(TOKEN_EPPEND, before)
end
@lexing_context[:epp_mode] = :text
interpolate_epp
else
emit(TOKEN_MODULO, before)
end
end,
'{' => lambda do
# The lexer needs to help the parser since the technology used cannot deal with
# lookahead of same token with different precedence. This is solved by making left brace
# after ? into a separate token.
#
@lexing_context[:brace_count] += 1
emit(if @lexing_context[:after] == :QMARK
TOKEN_SELBRACE
else
TOKEN_LBRACE
end, @scanner.pos)
end,
'}' => lambda do
@lexing_context[:brace_count] -= 1
emit(TOKEN_RBRACE, @scanner.pos)
end,
# TOKENS @, @@, @(
'@' => lambda do
scn = @scanner
la = scn.peek(2)
case la[1]
when '@'
emit(TOKEN_ATAT, scn.pos) # TODO; Check if this is good for the grammar
when '('
heredoc
else
emit(TOKEN_AT, scn.pos)
end
end,
# TOKENS |, |>, |>>
'|' => lambda do
scn = @scanner
la = scn.peek(3)
emit(if la[1] == '>'
la[2] == '>' ? TOKEN_RRCOLLECT : TOKEN_RCOLLECT
else
TOKEN_PIPE
end, scn.pos)
end,
# TOKENS =, =>, ==, =~
'=' => lambda do
scn = @scanner
la = scn.peek(2)
emit(case la[1]
when '='
TOKEN_ISEQUAL
when '>'
TOKEN_FARROW
when '~'
TOKEN_MATCH
else
TOKEN_EQUALS
end, scn.pos)
end,
# TOKENS '+', '+=', and '+>'
'+' => lambda do
scn = @scanner
la = scn.peek(2)
emit(case la[1]
when '='
TOKEN_APPENDS
when '>'
TOKEN_PARROW
else
TOKEN_PLUS
end, scn.pos)
end,
# TOKENS '-', '->', and epp '-%>' (end of interpolation with trim)
'-' => lambda do
scn = @scanner
la = scn.peek(3)
before = scn.pos
if @lexing_context[:epp_mode] && la[1] == '%' && la[2] == '>'
scn.pos += 3
if @lexing_context[:epp_mode] == :expr
enqueue_completed(TOKEN_EPPEND_TRIM, before)
end
interpolate_epp(:with_trim)
else
emit(case la[1]
when '>'
TOKEN_IN_EDGE
when '='
TOKEN_DELETES
else
TOKEN_MINUS
end, before)
end
end,
# TOKENS !, !=, !~
'!' => lambda do
scn = @scanner
la = scn.peek(2)
emit(case la[1]
when '='
TOKEN_NOTEQUAL
when '~'
TOKEN_NOMATCH
else
TOKEN_NOT
end, scn.pos)
end,
# TOKENS ~>, ~
'~' => lambda do
scn = @scanner
la = scn.peek(2)
emit(la[1] == '>' ? TOKEN_IN_EDGE_SUB : TOKEN_TILDE, scn.pos)
end,
'#' => -> { @scanner.skip(PATTERN_COMMENT); nil },
# TOKENS '/', '/*' and '/ regexp /'
'/' => lambda do
scn = @scanner
la = scn.peek(2)
if la[1] == '*'
lex_error(Issues::UNCLOSED_MLCOMMENT) if scn.skip(PATTERN_MLCOMMENT).nil?
nil
else
before = scn.pos
# regexp position is a regexp, else a div
value = scn.scan(PATTERN_REGEX) if regexp_acceptable?
if value
# Ensure an escaped / was not matched
while escaped_end(value)
more = scn.scan_until(PATTERN_REGEX_END)
return emit(TOKEN_DIV, before) unless more
value << more
end
regex = value.sub(PATTERN_REGEX_A, '').sub(PATTERN_REGEX_Z, '').gsub(PATTERN_REGEX_ESC, '/')
emit_completed([:REGEX, Regexp.new(regex), scn.pos - before], before)
else
emit(TOKEN_DIV, before)
end
end
end,
# TOKENS <, <=, <|, <<|, <<, <-, <~
'<' => lambda do
scn = @scanner
la = scn.peek(3)
emit(case la[1]
when '<'
if la[2] == '|'
TOKEN_LLCOLLECT
else
TOKEN_LSHIFT
end
when '='
TOKEN_LESSEQUAL
when '|'
TOKEN_LCOLLECT
when '-'
TOKEN_OUT_EDGE
when '~'
TOKEN_OUT_EDGE_SUB
else
TOKEN_LESSTHAN
end, scn.pos)
end,
# TOKENS >, >=, >>
'>' => lambda do
scn = @scanner
la = scn.peek(2)
emit(case la[1]
when '>'
TOKEN_RSHIFT
when '='
TOKEN_GREATEREQUAL
else
TOKEN_GREATERTHAN
end, scn.pos)
end,
# TOKENS :, ::CLASSREF, ::NAME
':' => lambda do
scn = @scanner
la = scn.peek(3)
before = scn.pos
if la[1] == ':'
# PERFORMANCE NOTE: This could potentially be speeded up by using a case/when listing all
# upper case letters. Alternatively, the 'A', and 'Z' comparisons may be faster if they are
# frozen.
#
la2 = la[2]
if la2 >= 'A' && la2 <= 'Z'
# CLASSREF or error
value = scn.scan(PATTERN_CLASSREF)
if value && scn.peek(2) != '::'
after = scn.pos
emit_completed([:CLASSREF, value.freeze, after - before], before)
else
# move to faulty position ('::<uc-letter>' was ok)
scn.pos = scn.pos + 3
lex_error(Issues::ILLEGAL_FULLY_QUALIFIED_CLASS_REFERENCE)
end
else
value = scn.scan(PATTERN_BARE_WORD)
if value
if value =~ PATTERN_NAME
emit_completed([:NAME, value.freeze, scn.pos - before], before)
else
emit_completed([:WORD, value.freeze, scn.pos - before], before)
end
else
# move to faulty position ('::' was ok)
scn.pos = scn.pos + 2
lex_error(Issues::ILLEGAL_FULLY_QUALIFIED_NAME)
end
end
else
emit(TOKEN_COLON, before)
end
end,
'$' => lambda do
scn = @scanner
before = scn.pos
value = scn.scan(PATTERN_DOLLAR_VAR)
if value
emit_completed([:VARIABLE, value[1..].freeze, scn.pos - before], before)
else
# consume the $ and let higher layer complain about the error instead of getting a syntax error
emit(TOKEN_VARIABLE_EMPTY, before)
end
end,
'"' => lambda do
# Recursive string interpolation, 'interpolate' either returns a STRING token, or
# a DQPRE with the rest of the string's tokens placed in the @token_queue
interpolate_dq
end,
"'" => lambda do
scn = @scanner
before = scn.pos
emit_completed([:STRING, slurp_sqstring.freeze, scn.pos - before], before)
end,
"\n" => lambda do
# If heredoc_cont is in effect there are heredoc text lines to skip over
# otherwise just skip the newline.
#
ctx = @lexing_context
if ctx[:newline_jump]
@scanner.pos = ctx[:newline_jump]
ctx[:newline_jump] = nil
else
@scanner.pos += 1
end
ctx[:line_lexical_start] = @scanner.pos
nil
end,
'' => -> { nil } # when the peek(1) returns empty
}
[' ', "\t", "\r"].each { |c| @selector[c] = -> { @scanner.skip(PATTERN_WS); nil } }
('0'..'9').each do |c|
@selector[c] = lambda do
scn = @scanner
before = scn.pos
value = scn.scan(PATTERN_NUMBER)
if value
length = scn.pos - before
assert_numeric(value, before)
emit_completed([:NUMBER, value.freeze, length], before)
else
invalid_number = scn.scan_until(PATTERN_NON_WS)
if before > 1
after = scn.pos
scn.pos = before - 1
if scn.peek(1) == '.'
# preceded by a dot. Is this a bad decimal number then?
scn.pos = before - 2
while scn.peek(1) =~ /^\d$/
invalid_number = nil
before = scn.pos
break if before == 0
scn.pos = scn.pos - 1
end
end
scn.pos = before
invalid_number ||= scn.peek(after - before)
end
assert_numeric(invalid_number, before)
scn.pos = before + 1
lex_error(Issues::ILLEGAL_NUMBER, { :value => invalid_number })
end
end
end
('a'..'z').to_a.push('_').each do |c|
@selector[c] = lambda do
scn = @scanner
before = scn.pos
value = scn.scan(PATTERN_BARE_WORD)
if value && value =~ PATTERN_NAME
emit_completed(KEYWORDS[value] || @taskm_keywords[value] || [:NAME, value.freeze, scn.pos - before], before)
elsif value
emit_completed([:WORD, value.freeze, scn.pos - before], before)
else
# move to faulty position ([a-z_] was ok)
scn.pos = scn.pos + 1
fully_qualified = scn.match?(/::/)
if fully_qualified
lex_error(Issues::ILLEGAL_FULLY_QUALIFIED_NAME)
else
lex_error(Issues::ILLEGAL_NAME_OR_BARE_WORD)
end
end
end
end
('A'..'Z').each do |c|
@selector[c] = lambda do
scn = @scanner
before = scn.pos
value = @scanner.scan(PATTERN_CLASSREF)
if value && @scanner.peek(2) != '::'
emit_completed([:CLASSREF, value.freeze, scn.pos - before], before)
else
# move to faulty position ([A-Z] was ok)
scn.pos = scn.pos + 1
lex_error(Issues::ILLEGAL_CLASS_REFERENCE)
end
end
end
@selector.default = lambda do
# In case of unicode spaces of various kinds that are captured by a regexp, but not by the
# simpler case expression above (not worth handling those special cases with better performance).
scn = @scanner
if scn.skip(PATTERN_WS)
nil
else
# "unrecognized char"
emit([:OTHER, scn.peek(0), 1], scn.pos)
end
end
@selector.each { |k, _v| k.freeze }
@selector.freeze
end
# Determine if last char of value is escaped by a backslash
def escaped_end(value)
escaped = false
if value.end_with?(STRING_BSLASH_SLASH)
value[1...-1].each_codepoint do |cp|
if cp == 0x5c # backslash
escaped = !escaped
else
escaped = false
end
end
end
escaped
end
# Clears the lexer state (it is not required to call this as it will be garbage collected
# and the next lex call (lex_string, lex_file) will reset the internal state.
#
def clear
# not really needed, but if someone wants to ensure garbage is collected as early as possible
@scanner = nil
@locator = nil
@lexing_context = nil
end
# Convenience method, and for compatibility with older lexer. Use the lex_string instead which allows
# passing the path to use without first having to call file= (which reads the file if it exists).
# (Bad form to use overloading of assignment operator for something that is not really an assignment. Also,
# overloading of = does not allow passing more than one argument).
#
def string=(string)
lex_string(string, nil)
end
def lex_string(string, path = nil)
initvars
assert_not_bom(string)
@scanner = StringScanner.new(string)
@locator = Locator.locator(string, path)
end
# Lexes an unquoted string.
# @param string [String] the string to lex
# @param locator [Locator] the locator to use (a default is used if nil is given)
# @param escapes [Array<String>] array of character strings representing the escape sequences to transform
# @param interpolate [Boolean] whether interpolation of expressions should be made or not.
#
def lex_unquoted_string(string, locator, escapes, interpolate)
initvars
assert_not_bom(string)
@scanner = StringScanner.new(string)
@locator = locator || Locator.locator(string, '')
@lexing_context[:escapes] = escapes || UQ_ESCAPES
@lexing_context[:uq_slurp_pattern] = if interpolate
escapes.include?('$') ? SLURP_UQ_PATTERN : SLURP_UQNE_PATTERN
else
SLURP_ALL_PATTERN
end
end
# Convenience method, and for compatibility with older lexer. Use the lex_file instead.
# (Bad form to use overloading of assignment operator for something that is not really an assignment).
#
def file=(file)
lex_file(file)
end
# TODO: This method should not be used, callers should get the locator since it is most likely required to
# compute line, position etc given offsets.
#
def file
@locator ? @locator.file : nil
end
# Initializes lexing of the content of the given file. An empty string is used if the file does not exist.
#
def lex_file(file)
initvars
contents = Puppet::FileSystem.exist?(file) ? Puppet::FileSystem.read(file, :mode => 'rb', :encoding => 'utf-8') : ''
assert_not_bom(contents)
@scanner = StringScanner.new(contents.freeze)
@locator = Locator.locator(contents, file)
end
def initvars
@token_queue = []
# NOTE: additional keys are used; :escapes, :uq_slurp_pattern, :newline_jump, :epp_*
@lexing_context = {
:brace_count => 0,
:after => nil,
:line_lexical_start => 0
}
# Use of --tasks introduces the new keyword 'plan'
@taskm_keywords = Puppet[:tasks] ? { 'plan' => [:PLAN, 'plan', 4], 'apply' => [:APPLY, 'apply', 5] }.freeze : EMPTY_HASH
end
# Scans all of the content and returns it in an array
# Note that the terminating [false, false] token is included in the result.
#
def fullscan
result = []
scan { |token| result.push(token) }
result
end
# A block must be passed to scan. It will be called with two arguments, a symbol for the token,
# and an instance of LexerSupport::TokenValue
# PERFORMANCE NOTE: The TokenValue is designed to reduce the amount of garbage / temporary data
# and to only convert the lexer's internal tokens on demand. It is slightly more costly to create an
# instance of a class defined in Ruby than an Array or Hash, but the gain is much bigger since transformation
# logic is avoided for many of its members (most are never used (e.g. line/pos information which is only of
# value in general for error messages, and for some expressions (which the lexer does not know about).
#
def scan
# PERFORMANCE note: it is faster to access local variables than instance variables.
# This makes a small but notable difference since instance member access is avoided for
# every token in the lexed content.
#
scn = @scanner
lex_error_without_pos(Issues::NO_INPUT_TO_LEXER) unless scn
ctx = @lexing_context
queue = @token_queue
selector = @selector
scn.skip(PATTERN_WS)
# This is the lexer's main loop
until queue.empty? && scn.eos?
token = queue.shift || selector[scn.peek(1)].call
if token
ctx[:after] = token[0]
yield token
end
end
# Signals end of input
yield [false, false]
end
# This lexes one token at the current position of the scanner.
# PERFORMANCE NOTE: Any change to this logic should be performance measured.
#
def lex_token
@selector[@scanner.peek(1)].call
end
# Emits (produces) a token [:tokensymbol, TokenValue] and moves the scanner's position past the token
#
def emit(token, byte_offset)
@scanner.pos = byte_offset + token[2]
[token[0], TokenValue.new(token, byte_offset, @locator)]
end
# Emits the completed token on the form [:tokensymbol, TokenValue. This method does not alter
# the scanner's position.
#
def emit_completed(token, byte_offset)
[token[0], TokenValue.new(token, byte_offset, @locator)]
end
# Enqueues a completed token at the given offset
def enqueue_completed(token, byte_offset)
@token_queue << emit_completed(token, byte_offset)
end
# Allows subprocessors for heredoc etc to enqueue tokens that are tokenized by a different lexer instance
#
def enqueue(emitted_token)
@token_queue << emitted_token
end
# Answers after which tokens it is acceptable to lex a regular expression.
# PERFORMANCE NOTE:
# It may be beneficial to turn this into a hash with default value of true for missing entries.
# A case expression with literal values will however create a hash internally. Since a reference is
# always needed to the hash, this access is almost as costly as a method call.
#
def regexp_acceptable?
case @lexing_context[:after]
# Ends of (potential) R-value generating expressions
when :RPAREN, :RBRACK, :RRCOLLECT, :RCOLLECT
false
# End of (potential) R-value - but must be allowed because of case expressions
# Called out here to not be mistaken for a bug.
when :RBRACE
true
# Operands (that can be followed by DIV (even if illegal in grammar)
when :NAME, :CLASSREF, :NUMBER, :STRING, :BOOLEAN, :DQPRE, :DQMID, :DQPOST, :HEREDOC, :REGEX, :VARIABLE, :WORD
false
else
true
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/serialization/json_path.rb | lib/puppet/pops/serialization/json_path.rb | # frozen_string_literal: true
require_relative '../../../puppet/concurrent/thread_local_singleton'
module Puppet::Pops
module Serialization
module JsonPath
# Creates a _json_path_ reference from the given `path` argument
#
# @path path [Array<Integer,String>] An array of integers and strings
# @return [String] the created json_path
#
# @api private
def self.to_json_path(path)
p = '$'.dup
path.each do |seg|
if seg.nil?
p << '[null]'
elsif Types::PScalarDataType::DEFAULT.instance?(seg)
p << '[' << Types::StringConverter.singleton.convert(seg, '%p') << ']'
else
# Unable to construct json path from complex segments
return nil
end
end
p
end
# Resolver for JSON path that uses the Puppet parser to create the AST. The path must start
# with '$' which denotes the value that is passed into the parser. This parser can easily
# be extended with more elaborate resolution mechanisms involving document sets.
#
# The parser is limited to constructs generated by the {JsonPath#to_json_path}
# method.
#
# @api private
class Resolver
extend Puppet::Concurrent::ThreadLocalSingleton
def initialize
@parser = Parser::Parser.new
@visitor = Visitor.new(nil, 'resolve', 2, 2)
end
# Resolve the given _path_ in the given _context_.
# @param context [Object] the context used for resolution
# @param path [String] the json path
# @return [Object] the resolved value
#
def resolve(context, path)
factory = @parser.parse_string(path)
v = resolve_any(factory.model.body, context, path)
v.is_a?(Builder) ? v.resolve : v
end
def resolve_any(ast, context, path)
@visitor.visit_this_2(self, ast, context, path)
end
def resolve_AccessExpression(ast, context, path)
bad_json_path(path) unless ast.keys.size == 1
receiver = resolve_any(ast.left_expr, context, path)
key = resolve_any(ast.keys[0], context, path)
if receiver.is_a?(Types::PuppetObject)
PCORE_TYPE_KEY == key ? receiver._pcore_type : receiver.send(key)
else
receiver[key]
end
end
def resolve_NamedAccessExpression(ast, context, path)
receiver = resolve_any(ast.left_expr, context, path)
key = resolve_any(ast.right_expr, context, path)
if receiver.is_a?(Types::PuppetObject)
PCORE_TYPE_KEY == key ? receiver._pcore_type : receiver.send(key)
else
receiver[key]
end
end
def resolve_QualifiedName(ast, _, _)
v = ast.value
'null' == v ? nil : v
end
def resolve_QualifiedReference(ast, _, _)
v = ast.cased_value
'null'.casecmp(v) == 0 ? nil : v
end
def resolve_ReservedWord(ast, _, _)
ast.word
end
def resolve_LiteralUndef(_, _, _)
'undef'
end
def resolve_LiteralDefault(_, _, _)
'default'
end
def resolve_VariableExpression(ast, context, path)
# A single '$' means root, i.e. the context.
bad_json_path(path) unless EMPTY_STRING == resolve_any(ast.expr, context, path)
context
end
def resolve_CallMethodExpression(ast, context, path)
bad_json_path(path) unless ast.arguments.empty?
resolve_any(ast.functor_expr, context, path)
end
def resolve_LiteralValue(ast, _, _)
ast.value
end
def resolve_Object(ast, _, path)
bad_json_path(path)
end
def bad_json_path(path)
raise SerializationError, _('Unable to parse jsonpath "%{path}"') % { :path => path }
end
private :bad_json_path
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/serialization/abstract_reader.rb | lib/puppet/pops/serialization/abstract_reader.rb | # frozen_string_literal: true
require_relative 'extension'
require_relative 'time_factory'
module Puppet::Pops
module Serialization
# Abstract class for protocol specific readers such as MsgPack or JSON
# The abstract reader is capable of reading the primitive scalars:
# - Boolean
# - Integer
# - Float
# - String
# and, by using extensions, also
# - Array start
# - Map start
# - Object start
# - Regexp
# - Version
# - VersionRange
# - Timespan
# - Timestamp
# - Default
#
# @api public
class AbstractReader
# @param [MessagePack::Unpacker,JSON::Unpacker] unpacker The low lever unpacker that delivers the primitive objects
# @param [MessagePack::Unpacker,JSON::Unpacker] extension_unpacker Optional unpacker for extensions. Defaults to the unpacker
# @api public
def initialize(unpacker, extension_unpacker = nil)
@read = []
@unpacker = unpacker
@extension_unpacker = extension_unpacker.nil? ? unpacker : extension_unpacker
register_types
end
# Read an object from the underlying unpacker
# @return [Object] the object that was read
# @api public
def read
obj = @unpacker.read
case obj
when Extension::InnerTabulation
@read[obj.index]
when Numeric, Symbol, Extension::NotTabulated, true, false, nil
# not tabulated
obj
else
@read << obj
obj
end
end
# @return [Integer] The total count of unique primitive values that has been read
# @api private
def primitive_count
@read.size
end
# @api private
def read_payload(data)
raise SerializationError, "Internal error: Class #{self.class} does not implement method 'read_payload'"
end
# @api private
def read_tpl_qname(ep)
Array.new(ep.read) { read_tpl(ep) }.join('::')
end
# @api private
def read_tpl(ep)
obj = ep.read
case obj
when Integer
@read[obj]
else
@read << obj
obj
end
end
# @api private
def extension_unpacker
@extension_unpacker
end
# @api private
def register_type(extension_number, &block)
@unpacker.register_type(extension_number, &block)
end
# @api private
def register_types
register_type(Extension::INNER_TABULATION) do |data|
read_payload(data) { |ep| Extension::InnerTabulation.new(ep.read) }
end
register_type(Extension::TABULATION) do |data|
read_payload(data) { |ep| Extension::Tabulation.new(ep.read) }
end
register_type(Extension::ARRAY_START) do |data|
read_payload(data) { |ep| Extension::ArrayStart.new(ep.read) }
end
register_type(Extension::MAP_START) do |data|
read_payload(data) { |ep| Extension::MapStart.new(ep.read) }
end
register_type(Extension::PCORE_OBJECT_START) do |data|
read_payload(data) { |ep| type_name = read_tpl_qname(ep); Extension::PcoreObjectStart.new(type_name, ep.read) }
end
register_type(Extension::OBJECT_START) do |data|
read_payload(data) { |ep| Extension::ObjectStart.new(ep.read) }
end
register_type(Extension::DEFAULT) do |data|
read_payload(data) { |_ep| Extension::Default::INSTANCE }
end
register_type(Extension::COMMENT) do |data|
read_payload(data) { |ep| Extension::Comment.new(ep.read) }
end
register_type(Extension::SENSITIVE_START) do |data|
read_payload(data) { |_ep| Extension::SensitiveStart::INSTANCE }
end
register_type(Extension::REGEXP) do |data|
read_payload(data) { |ep| Regexp.new(ep.read) }
end
register_type(Extension::TYPE_REFERENCE) do |data|
read_payload(data) { |ep| Types::PTypeReferenceType.new(ep.read) }
end
register_type(Extension::SYMBOL) do |data|
read_payload(data) { |ep| ep.read.to_sym }
end
register_type(Extension::TIME) do |data|
read_payload(data) do |ep|
sec = ep.read
nsec = ep.read
Time::Timestamp.new(sec * 1_000_000_000 + nsec)
end
end
register_type(Extension::TIMESPAN) do |data|
read_payload(data) do |ep|
sec = ep.read
nsec = ep.read
Time::Timespan.new(sec * 1_000_000_000 + nsec)
end
end
register_type(Extension::VERSION) do |data|
read_payload(data) { |ep| SemanticPuppet::Version.parse(ep.read) }
end
register_type(Extension::VERSION_RANGE) do |data|
read_payload(data) { |ep| SemanticPuppet::VersionRange.parse(ep.read) }
end
register_type(Extension::BASE64) do |data|
read_payload(data) { |ep| Types::PBinaryType::Binary.from_base64_strict(ep.read) }
end
register_type(Extension::BINARY) do |data|
# The Ruby MessagePack implementation have special treatment for "ASCII-8BIT" strings. They
# are written as binary data.
read_payload(data) { |ep| Types::PBinaryType::Binary.new(ep.read) }
end
register_type(Extension::URI) do |data|
read_payload(data) { |ep| URI(ep.read) }
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/serialization/instance_writer.rb | lib/puppet/pops/serialization/instance_writer.rb | # frozen_string_literal: true
module Puppet::Pops
module Serialization
# An instance writer is responsible for writing complex objects using a {Serializer}
# @api private
module InstanceWriter
# @param [Types::PObjectType] type the type of instance to write
# @param [Object] value the instance
# @param [Serializer] serializer the serializer that will receive the written instance
def write(type, value, serializer)
Serialization.not_implemented(self, 'write')
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/serialization/time_factory.rb | lib/puppet/pops/serialization/time_factory.rb | # frozen_string_literal: true
module Puppet::Pops
module Serialization
# Implements all the constructors found in the Time class and ensures that
# the created Time object can be serialized and deserialized using its
# seconds and nanoseconds without loss of precision.
#
# @deprecated No longer in use. Functionality replaced by Timestamp
# @api private
class TimeFactory
NANO_DENOMINATOR = 10**9
def self.at(*args)
sec_nsec_safe(Time.at(*args))
end
def self.gm(*args)
sec_nsec_safe(Time.gm(*args))
end
def self.local(*args)
sec_nsec_safe(Time.local(*args))
end
def self.mktime(*args)
sec_nsec_safe(Time.mktime(*args))
end
def self.new(*args)
sec_nsec_safe(Time.new(*args))
end
def self.now
sec_nsec_safe(Time.now)
end
def self.utc(*args)
sec_nsec_safe(Time.utc(*args))
end
# Creates a Time object from a Rational defined as:
#
# (_sec_ * #NANO_DENOMINATOR + _nsec_) / #NANO_DENOMINATOR
#
# This ensures that a Time object can be reliably serialized and using its
# its #tv_sec and #tv_nsec values and then recreated again (using this method)
# without loss of precision.
#
# @param sec [Integer] seconds since Epoch
# @param nsec [Integer] nano seconds
# @return [Time] the created object
#
def self.from_sec_nsec(sec, nsec)
Time.at(Rational(sec * NANO_DENOMINATOR + nsec, NANO_DENOMINATOR))
end
# Returns a new Time object that is adjusted to ensure that precision is not
# lost when it is serialized and deserialized using its seconds and nanoseconds
# @param t [Time] the object to adjust
# @return [Time] the adjusted object
#
def self.sec_nsec_safe(t)
from_sec_nsec(t.tv_sec, t.tv_nsec)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/serialization/abstract_writer.rb | lib/puppet/pops/serialization/abstract_writer.rb | # frozen_string_literal: true
require_relative 'extension'
module Puppet::Pops
module Serialization
MAX_INTEGER = 0x7fffffffffffffff
MIN_INTEGER = -0x8000000000000000
# Abstract class for protocol specific writers such as MsgPack or JSON
# The abstract write is capable of writing the primitive scalars:
# - Boolean
# - Integer
# - Float
# - String
# and, by using extensions, also
# - Array start
# - Map start
# - Object start
# - Regexp
# - Version
# - VersionRange
# - Timespan
# - Timestamp
# - Default
#
# @api public
class AbstractWriter
# @param [MessagePack::Packer,JSON::Packer] packer the underlying packer stream
# @param [Hash] options
# @option options [Boolean] :tabulate `true` if tabulation is enabled (which is the default).
# @param [DebugPacker,nil] extension_packer Optional specific extension packer. Only used for debug output
# @api public
def initialize(packer, options, extension_packer = nil)
@tabulate = options[:tabulate]
@tabulate = true if @tabulate.nil?
@written = {}
@packer = packer
@extension_packer = extension_packer.nil? ? packer : extension_packer
register_types
end
# Tell the underlying packer to flush.
# @api public
def finish
@packer.flush
end
def supports_binary?
false
end
# Write a value on the underlying stream
# @api public
def write(value)
written = false
case value
when Integer
# not tabulated, but integers larger than 64-bit cannot be allowed.
raise SerializationError, _('Integer out of bounds') if value > MAX_INTEGER || value < MIN_INTEGER
when Numeric, Symbol, Extension::NotTabulated, true, false, nil
# not tabulated
else
if @tabulate
index = @written[value]
if index.nil?
@packer.write(value)
written = true
@written[value] = @written.size
else
value = Extension::InnerTabulation.new(index)
end
end
end
@packer.write(value) unless written
end
# Called from extension callbacks only
#
# @api private
def build_payload
raise SerializationError, "Internal error: Class #{self.class} does not implement method 'build_payload'"
end
# @api private
def extension_packer
@extension_packer
end
# Called from extension callbacks only
#
# @api private
def write_tpl_qname(ep, qname)
names = qname.split('::')
ep.write(names.size)
names.each { |n| write_tpl(ep, n) }
end
# Called from extension callbacks only
#
# @api private
def write_tpl(ep, value)
# TRANSLATORS 'Integers' is a Ruby class for numbers and should not be translated
raise ArgumentError, _('Internal error. Integers cannot be tabulated in extension payload') if value.is_a?(Integer)
if @tabulate
index = @written[value]
if index.nil?
@written[value] = @written.size
else
value = index
end
end
ep.write(value)
end
# @api private
def register_type(extension_number, payload_class, &block)
@packer.register_type(extension_number, payload_class, &block)
end
# @api private
def register_types
# 0x00 - 0x0F are reserved for low-level serialization / tabulation extensions
register_type(Extension::INNER_TABULATION, Extension::InnerTabulation) do |o|
build_payload { |ep| ep.write(o.index) }
end
register_type(Extension::TABULATION, Extension::Tabulation) do |o|
build_payload { |ep| ep.write(o.index) }
end
# 0x10 - 0x1F are reserved for structural extensions
register_type(Extension::ARRAY_START, Extension::ArrayStart) do |o|
build_payload { |ep| ep.write(o.size) }
end
register_type(Extension::MAP_START, Extension::MapStart) do |o|
build_payload { |ep| ep.write(o.size) }
end
register_type(Extension::PCORE_OBJECT_START, Extension::PcoreObjectStart) do |o|
build_payload { |ep| write_tpl_qname(ep, o.type_name); ep.write(o.attribute_count) }
end
register_type(Extension::OBJECT_START, Extension::ObjectStart) do |o|
build_payload { |ep| ep.write(o.attribute_count) }
end
# 0x20 - 0x2f reserved for special extension objects
register_type(Extension::DEFAULT, Extension::Default) do |_o|
build_payload { |ep| }
end
register_type(Extension::COMMENT, Extension::Comment) do |o|
build_payload { |ep| ep.write(o.comment) }
end
register_type(Extension::SENSITIVE_START, Extension::SensitiveStart) do |_o|
build_payload { |ep| }
end
# 0x30 - 0x7f reserved for mapping of specific runtime classes
register_type(Extension::REGEXP, Regexp) do |o|
build_payload { |ep| ep.write(o.source) }
end
register_type(Extension::TYPE_REFERENCE, Types::PTypeReferenceType) do |o|
build_payload { |ep| ep.write(o.type_string) }
end
register_type(Extension::SYMBOL, Symbol) do |o|
build_payload { |ep| ep.write(o.to_s) }
end
register_type(Extension::TIME, Time::Timestamp) do |o|
build_payload { |ep| nsecs = o.nsecs; ep.write(nsecs / 1_000_000_000); ep.write(nsecs % 1_000_000_000) }
end
register_type(Extension::TIMESPAN, Time::Timespan) do |o|
build_payload { |ep| nsecs = o.nsecs; ep.write(nsecs / 1_000_000_000); ep.write(nsecs % 1_000_000_000) }
end
register_type(Extension::VERSION, SemanticPuppet::Version) do |o|
build_payload { |ep| ep.write(o.to_s) }
end
register_type(Extension::VERSION_RANGE, SemanticPuppet::VersionRange) do |o|
build_payload { |ep| ep.write(o.to_s) }
end
if supports_binary?
register_type(Extension::BINARY, Types::PBinaryType::Binary) do |o|
# The Ruby MessagePack implementation has special treatment for "ASCII-8BIT" strings. They
# are written as binary data.
build_payload { |ep| ep.write(o.binary_buffer) }
end
else
register_type(Extension::BASE64, Types::PBinaryType::Binary) do |o|
build_payload { |ep| ep.write(o.to_s) }
end
end
URI.scheme_list.values.each do |uri_class|
register_type(Extension::URI, uri_class) do |o|
build_payload { |ep| ep.write(o.to_s) }
end
end
end
def to_s
self.class.name.to_s
end
def inspect
to_s
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/serialization/to_data_converter.rb | lib/puppet/pops/serialization/to_data_converter.rb | # frozen_string_literal: true
module Puppet::Pops
module Serialization
# Class that can process an arbitrary object into a value that is assignable to `Data`.
#
# @api public
class ToDataConverter
include Evaluator::Runtime3Support
# Convert the given _value_ according to the given _options_ and return the result of the conversion
#
# @param value [Object] the value to convert
# @param options {Symbol => <Boolean,String>} options hash
# @option options [Boolean] :rich_data `true` if rich data is enabled
# @option options [Boolean] :local_reference use local references instead of duplicating complex entries
# @option options [Boolean] :type_by_reference `true` if Object types are converted to references rather than embedded.
# @option options [Boolean] :symbol_as_string `true` if Symbols should be converted to strings (with type loss)
# @option options [String] :message_prefix String to prepend to in warnings and errors
# @return [Data] the processed result. An object assignable to `Data`.
#
# @api public
def self.convert(value, options = EMPTY_HASH)
new(options).convert(value)
end
# Create a new instance of the processor
#
# @param options {Symbol => Object} options hash
# @option options [Boolean] :rich_data `true` if rich data is enabled
# @option options [Boolean] :local_references use local references instead of duplicating complex entries
# @option options [Boolean] :type_by_reference `true` if Object types are converted to references rather than embedded.
# @option options [Boolean] :symbol_as_string `true` if Symbols should be converted to strings (with type loss)
# @option options [String] :message_prefix String to prepend to path in warnings and errors
# @option semantic [Object] :semantic object to pass to the issue reporter
def initialize(options = EMPTY_HASH)
@type_by_reference = options[:type_by_reference]
@type_by_reference = true if @type_by_reference.nil?
@local_reference = options[:local_reference]
@local_reference = true if @local_reference.nil?
@symbol_as_string = options[:symbol_as_string]
@symbol_as_string = false if @symbol_as_string.nil?
@rich_data = options[:rich_data]
@rich_data = false if @rich_data.nil?
@message_prefix = options[:message_prefix]
@semantic = options[:semantic]
end
# Convert the given _value_
#
# @param value [Object] the value to convert
# @return [Data] the processed result. An object assignable to `Data`.
#
# @api public
def convert(value)
@path = []
@values = {}
to_data(value)
end
private
def path_to_s
s = String.new(@message_prefix || '')
s << JsonPath.to_json_path(@path)[1..]
s
end
def to_data(value)
if value.nil? || Types::PScalarDataType::DEFAULT.instance?(value)
if @rich_data && value.is_a?(String) && value.encoding == Encoding::ASCII_8BIT
# Transform the binary string to rich Binary
{
PCORE_TYPE_KEY => PCORE_TYPE_BINARY,
PCORE_VALUE_KEY => Puppet::Pops::Types::PBinaryType::Binary.from_binary_string(value).to_s
}
else
value
end
elsif :default == value
if @rich_data
{ PCORE_TYPE_KEY => PCORE_TYPE_DEFAULT }
else
serialization_issue(Issues::SERIALIZATION_DEFAULT_CONVERTED_TO_STRING, :path => path_to_s)
'default'
end
elsif value.is_a?(Symbol)
if @symbol_as_string
value.to_s
elsif @rich_data
{ PCORE_TYPE_KEY => PCORE_TYPE_SYMBOL, PCORE_VALUE_KEY => value.to_s }
else
unknown_to_string_with_warning(value)
end
elsif value.instance_of?(Array)
process(value) do
result = []
value.each_with_index do |elem, index|
with(index) { result << to_data(elem) }
end
result
end
elsif value.instance_of?(Hash)
process(value) do
if value.keys.all? { |key| key.is_a?(String) && key != PCORE_TYPE_KEY }
result = {}
value.each_pair { |key, elem| with(key) { result[key] = to_data(elem) } }
result
else
non_string_keyed_hash_to_data(value)
end
end
elsif value.instance_of?(Types::PSensitiveType::Sensitive)
process(value) do
{ PCORE_TYPE_KEY => PCORE_TYPE_SENSITIVE, PCORE_VALUE_KEY => to_data(value.unwrap) }
end
else
unknown_to_data(value)
end
end
# If `:local_references` is enabled, then the `object_id` will be associated with the current _path_ of
# the context the first time this method is called. The method then returns the result of yielding to
# the given block. Subsequent calls with a value that has the same `object_id` will instead return a
# reference based on the given path.
#
# If `:local_references` is disabled, then this method performs a check for endless recursion before
# it yields to the given block. The result of yielding is returned.
#
# @param value [Object] the value
# @yield The block that will produce the data for the value
# @return [Data] the result of yielding to the given block, or a hash denoting a reference
#
# @api private
def process(value, &block)
if @local_reference
id = value.object_id
ref = @values[id]
if ref.nil?
@values[id] = @path.dup
yield
elsif ref.instance_of?(Hash)
ref
else
json_ref = JsonPath.to_json_path(ref)
if json_ref.nil?
# Complex key and hence no way to reference the prior value. The value must therefore be
# duplicated which in turn introduces a risk for endless recursion in case of self
# referencing structures
with_recursive_guard(value, &block)
else
@values[id] = { PCORE_TYPE_KEY => PCORE_LOCAL_REF_SYMBOL, PCORE_VALUE_KEY => json_ref }
end
end
else
with_recursive_guard(value, &block)
end
end
# Pushes `key` to the end of the path and yields to the given block. The
# `key` is popped when the yield returns.
# @param key [Object] the key to push on the current path
# @yield The block that will produce the returned value
# @return [Object] the result of yielding to the given block
#
# @api private
def with(key)
@path.push(key)
value = yield
@path.pop
value
end
# @param value [Object] the value to use when checking endless recursion
# @yield The block that will produce the data
# @return [Data] the result of yielding to the given block
def with_recursive_guard(value)
id = value.object_id
if @recursive_lock
if @recursive_lock.include?(id)
serialization_issue(Issues::SERIALIZATION_ENDLESS_RECURSION, :type_name => value.class.name)
end
@recursive_lock[id] = true
else
@recursive_lock = { id => true }
end
v = yield
@recursive_lock.delete(id)
v
end
def unknown_to_data(value)
@rich_data ? value_to_data_hash(value) : unknown_to_string_with_warning(value)
end
def unknown_key_to_string_with_warning(value)
str = unknown_to_string(value)
serialization_issue(Issues::SERIALIZATION_UNKNOWN_KEY_CONVERTED_TO_STRING, :path => path_to_s, :klass => value.class, :value => str)
str
end
def unknown_to_string_with_warning(value)
str = unknown_to_string(value)
serialization_issue(Issues::SERIALIZATION_UNKNOWN_CONVERTED_TO_STRING, :path => path_to_s, :klass => value.class, :value => str)
str
end
def unknown_to_string(value)
value.is_a?(Regexp) ? Puppet::Pops::Types::PRegexpType.regexp_to_s_with_delimiters(value) : value.to_s
end
def non_string_keyed_hash_to_data(hash)
if @rich_data
to_key_extended_hash(hash)
else
result = {}
hash.each_pair do |key, value|
if key.is_a?(Symbol) && @symbol_as_string
key = key.to_s
elsif !key.is_a?(String)
key = unknown_key_to_string_with_warning(key)
end
with(key) { result[key] = to_data(value) }
end
result
end
end
# A Key extended hash is a hash whose keys are not entirely strings. Such a hash
# cannot be safely represented as JSON or YAML
#
# @param hash {Object => Object} the hash to process
# @return [String => Data] the representation of the extended hash
def to_key_extended_hash(hash)
key_value_pairs = []
hash.each_pair do |key, value|
key = to_data(key)
key_value_pairs << key
key_value_pairs << with(key) { to_data(value) }
end
{ PCORE_TYPE_KEY => PCORE_TYPE_HASH, PCORE_VALUE_KEY => key_value_pairs }
end
def value_to_data_hash(value)
pcore_type = value.is_a?(Types::PuppetObject) ? value._pcore_type : Types::TypeCalculator.singleton.infer(value)
if pcore_type.is_a?(Puppet::Pops::Types::PRuntimeType)
unknown_to_string_with_warning(value)
else
pcore_tv = pcore_type_to_data(pcore_type)
if pcore_type.roundtrip_with_string?
{
PCORE_TYPE_KEY => pcore_tv,
# Scalar values are stored using their default string representation
PCORE_VALUE_KEY => Types::StringConverter.singleton.convert(value)
}
elsif pcore_type.implementation_class.respond_to?(:_pcore_init_from_hash)
process(value) do
{
PCORE_TYPE_KEY => pcore_tv,
}.merge(to_data(value._pcore_init_hash))
end
else
process(value) do
(names, _, required_count) = pcore_type.parameter_info(value.class)
args = names.map { |name| value.send(name) }
# Pop optional arguments that are default
while args.size > required_count
break unless pcore_type[names[args.size - 1]].default_value?(args.last)
args.pop
end
result = {
PCORE_TYPE_KEY => pcore_tv
}
args.each_with_index do |val, idx|
key = names[idx]
with(key) { result[key] = to_data(val) }
end
result
end
end
end
end
def pcore_type_to_data(pcore_type)
type_name = pcore_type.name
if @type_by_reference || type_name.start_with?('Pcore::')
type_name
else
with(PCORE_TYPE_KEY) { to_data(pcore_type) }
end
end
private :pcore_type_to_data
def serialization_issue(issue, options = EMPTY_HASH)
semantic = @semantic
if semantic.nil?
tos = Puppet::Pops::PuppetStack.top_of_stack
if tos.empty?
semantic = Puppet::Pops::SemanticError.new(issue, nil, EMPTY_HASH)
else
file, line = stacktrace
semantic = Puppet::Pops::SemanticError.new(issue, nil, { :file => file, :line => line })
end
end
optionally_fail(issue, semantic, options)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/serialization/json.rb | lib/puppet/pops/serialization/json.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/json'
module Puppet::Pops
module Serialization
require_relative 'time_factory'
require_relative 'abstract_reader'
require_relative 'abstract_writer'
module JSON
# A Writer that writes output in JSON format
# @api private
class Writer < AbstractWriter
def initialize(io, options = {})
super(Packer.new(io, options), options)
end
# Clear the underlying io stream but does not clear tabulation cache
# Specifically designed to enable tabulation to span more than one
# separately deserialized object.
def clear_io
@packer.clear_io
end
def extension_packer
@packer
end
def packer
@packer
end
def build_payload
yield(@packer)
end
def to_a
@packer.to_a
end
def to_json
@packer.to_json
end
end
# A Reader that reads JSON formatted input
# @api private
class Reader < AbstractReader
def initialize(io)
super(Unpacker.new(io))
end
def re_initialize(io)
@unpacker.re_initialize(io)
end
def read_payload(data)
yield(@unpacker)
end
end
# The JSON Packer. Modeled after the MessagePack::Packer
# @api private
class Packer
def initialize(io, options = {})
@io = io
@io << '['
@type_registry = {}
@nested = []
@verbose = options[:verbose]
@verbose = false if @verbose.nil?
@indent = options[:indent] || 0
end
def register_type(type, klass, &block)
@type_registry[klass] = [type, klass, block]
end
def clear_io
# Truncate everything except leading '['
if @io.is_a?(String)
@io.slice!(1..-1)
else
@io.truncate(1)
end
end
def empty?
@io.is_a?(String) ? io.length == 1 : @io.pos == 1
end
def flush
# Drop last comma unless just start marker present
if @io.is_a?(String)
@io.chop! unless @io.length == 1
@io << ']'
else
pos = @io.pos
@io.pos = pos - 1 unless pos == 1
@io << ']'
@io.flush
end
end
def write(obj)
case obj
when Array
write_array_header(obj.size)
obj.each { |x| write(x) }
when Hash
write_map_header(obj.size)
obj.each_pair { |k, v| write(k); write(v) }
when nil
write_nil
else
write_scalar(obj)
end
end
alias pack write
def write_array_header(n)
if n < 1
@io << '[]'
else
@io << '['
@nested << [false, n]
end
end
def write_map_header(n)
if n < 1
@io << '{}'
else
@io << '{'
@nested << [true, n * 2]
end
end
def write_nil
@io << 'null'
write_delim
end
def to_s
to_json
end
def to_a
::Puppet::Util::Json.load(io_string)
end
def to_json
if @indent > 0
::Puppet::Util::Json.dump(to_a, { :pretty => true, :indent => ' ' * @indent })
else
io_string
end
end
# Write a payload object. Not subject to extensions
def write_pl(obj)
@io << Puppet::Util::Json.dump(obj) << ','
end
def io_string
if @io.is_a?(String)
@io
else
@io.pos = 0
@io.read
end
end
private :io_string
def write_delim
nesting = @nested.last
cnt = nesting.nil? ? nil : nesting[1]
case cnt
when 1
@io << (nesting[0] ? '}' : ']')
@nested.pop
write_delim
when Integer
if cnt.even? || !nesting[0]
@io << ','
else
@io << ':'
end
nesting[1] = cnt - 1
else
@io << ','
end
end
private :write_delim
def write_scalar(obj)
ext = @type_registry[obj.class]
if ext.nil?
case obj
when Numeric, String, true, false, nil
@io << Puppet::Util::Json.dump(obj)
write_delim
else
raise SerializationError, _("Unable to serialize a %{obj}") % { obj: obj.class.name }
end
else
write_extension(ext, obj)
end
end
private :write_scalar
def write_extension(ext, obj)
@io << '[' << extension_indicator(ext).to_json << ','
@nested << nil
write_extension_payload(ext, obj)
@nested.pop
if obj.is_a?(Extension::SequenceStart) && obj.sequence_size > 0
@nested << [false, obj.sequence_size]
else
if @io.is_a?(String)
@io.chop!
else
@io.pos -= 1
end
@io << ']'
write_delim
end
end
private :write_extension
def write_extension_payload(ext, obj)
ext[2].call(obj)
end
private :write_extension_payload
def extension_indicator(ext)
@verbose ? ext[1].name.sub(/^Puppet::Pops::Serialization::\w+::(.+)$/, '\1') : ext[0]
end
private :extension_indicator
end
class Unpacker
def initialize(io)
re_initialize(io)
@type_registry = {}
@nested = []
end
def re_initialize(io)
parsed = parse_io(io)
raise SerializationError, _("JSON stream is not an array. It is a %{klass}") % { klass: io.class.name } unless parsed.is_a?(Array)
@etor_stack = [parsed.each]
end
def read
obj = nil
loop do
raise SerializationError, _('Unexpected end of input') if @etor_stack.empty?
etor = @etor_stack.last
begin
obj = etor.next
break
rescue StopIteration
@etor_stack.pop
end
end
if obj.is_a?(Array)
ext_etor = obj.each
@etor_stack << ext_etor
ext_no = ext_etor.next
ext_block = @type_registry[ext_no]
raise SerializationError, _("Invalid input. %{ext_no} is not a valid extension number") % { ext_no: ext_no } if ext_block.nil?
obj = ext_block.call(nil)
end
obj
end
def register_type(extension_number, &block)
@type_registry[extension_number] = block
end
private
def parse_io(io)
case io
when IO, StringIO
::Puppet::Util::Json.load(io.read)
when String
::Puppet::Util::Json.load(io)
else
io
end
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/serialization/serializer.rb | lib/puppet/pops/serialization/serializer.rb | # frozen_string_literal: true
require_relative 'extension'
module Puppet::Pops
module Serialization
# The serializer is capable of writing, arrays, maps, and complex objects using an underlying protocol writer. It takes care of
# tabulating and disassembling complex objects.
# @api public
class Serializer
# Provides access to the writer.
# @api private
attr_reader :writer
# @param writer [AbstractWriter] the writer that is used for writing primitive values
# @param options [{String, Object}] serialization options
# @option options [Boolean] :type_by_reference `true` if Object types are serialized by name only.
# @api public
def initialize(writer, options = EMPTY_HASH)
# Hash#compare_by_identity is intentionally not used since we only need to map
# object ids to their size and we don't want to store entire objects in memory
@written = {}
@writer = writer
@options = options
end
# Tell the underlying writer to finish
# @api public
def finish
@writer.finish
end
# Write an object
# @param [Object] value the object to write
# @api public
def write(value)
case value
when Integer, Float, String, true, false, nil
@writer.write(value)
when :default
@writer.write(Extension::Default::INSTANCE)
else
index = @written[value.object_id] # rubocop:disable Lint/HashCompareByIdentity
if index.nil?
write_tabulated_first_time(value)
else
@writer.write(Extension::Tabulation.new(index))
end
end
end
# Write the start of an array.
# @param [Integer] size the size of the array
# @api private
def start_array(size)
@writer.write(Extension::ArrayStart.new(size))
end
# Write the start of a map (hash).
# @param [Integer] size the number of entries in the map
# @api private
def start_map(size)
@writer.write(Extension::MapStart.new(size))
end
# Write the start of a complex pcore object
# @param [String] type_ref the name of the type
# @param [Integer] attr_count the number of attributes in the object
# @api private
def start_pcore_object(type_ref, attr_count)
@writer.write(Extension::PcoreObjectStart.new(type_ref, attr_count))
end
# Write the start of a complex object
# @param [Integer] attr_count the number of attributes in the object
# @api private
def start_object(attr_count)
@writer.write(Extension::ObjectStart.new(attr_count))
end
def push_written(value)
@written[value.object_id] = @written.size # rubocop:disable Lint/HashCompareByIdentity
end
# Write the start of a sensitive object
# @api private
def start_sensitive
@writer.write(Extension::SensitiveStart::INSTANCE)
end
def type_by_reference?
@options[:type_by_reference] == true
end
def to_s
"#{self.class.name} with #{@writer}"
end
def inspect
to_s
end
# First time write of a tabulated object. This means that the object is written and then remembered. Subsequent writes
# of the same object will yield a write of a tabulation index instead.
# @param [Object] value the value to write
# @api private
def write_tabulated_first_time(value)
if value.instance_of?(Symbol) ||
value.instance_of?(Regexp) ||
value.instance_of?(SemanticPuppet::Version) ||
value.instance_of?(SemanticPuppet::VersionRange) ||
value.instance_of?(Time::Timestamp) ||
value.instance_of?(Time::Timespan) ||
value.instance_of?(Types::PBinaryType::Binary) ||
value.is_a?(URI)
push_written(value)
@writer.write(value)
elsif value.instance_of?(Array)
push_written(value)
start_array(value.size)
value.each { |elem| write(elem) }
elsif value.instance_of?(Hash)
push_written(value)
start_map(value.size)
value.each_pair { |key, val| write(key); write(val) }
elsif value.instance_of?(Types::PSensitiveType::Sensitive)
start_sensitive
write(value.unwrap)
elsif value.instance_of?(Types::PTypeReferenceType)
push_written(value)
@writer.write(value)
elsif value.is_a?(Types::PuppetObject)
value._pcore_type.write(value, self)
else
impl_class = value.class
type = Loaders.implementation_registry.type_for_module(impl_class)
raise SerializationError, _("No Puppet Type found for %{klass}") % { klass: impl_class.name } unless type.is_a?(Types::PObjectType)
type.write(value, self)
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/serialization/from_data_converter.rb | lib/puppet/pops/serialization/from_data_converter.rb | # frozen_string_literal: true
module Puppet::Pops
module Serialization
class Builder
def initialize(values)
@values = values
@resolved = true
end
def [](key)
@values[key]
end
def []=(key, value)
@values[key] = value
@resolved = false if value.is_a?(Builder)
end
def resolve
unless @resolved
@resolved = true
case @values
when Array
@values.each_with_index { |v, idx| @values[idx] = v.resolve if v.is_a?(Builder) }
when Hash
@values.each_pair { |k, v| @values[k] = v.resolve if v.is_a?(Builder) }
end
end
@values
end
end
class ObjectHashBuilder < Builder
def initialize(instance)
super({})
@instance = instance
end
def resolve
@instance._pcore_init_from_hash(super)
@instance
end
end
class ObjectArrayBuilder < Builder
def initialize(instance)
super({})
@instance = instance
end
def resolve
@instance.send(:initialize, *super.values)
@instance
end
end
# Class that can process the `Data` produced by the {ToDataConverter} class and reassemble
# the objects that were converted.
#
# @api public
class FromDataConverter
# Converts the given `Data` _value_ according to the given _options_ and returns the resulting `RichData`.
#
# @param value [Data] the value to convert
# @param options {Symbol => <Boolean,String>} options hash
# @option options [Loaders::Loader] :loader the loader to use. Can be `nil` in which case the default is
# determined by the {Types::TypeParser}.
# @option options [Boolean] :allow_unresolved `true` to allow that rich_data hashes are kept "as is" if the
# designated '__ptype' cannot be resolved. Defaults to `false`.
# @return [RichData] the processed result.
#
# @api public
def self.convert(value, options = EMPTY_HASH)
new(options).convert(value)
end
# Creates a new instance of the processor
#
# @param options {Symbol => Object} options hash
# @option options [Loaders::Loader] :loader the loader to use. Can be `nil` in which case the default is
# determined by the {Types::TypeParser}.
# @option options [Boolean] :allow_unresolved `true` to allow that rich_data hashes are kept "as is" if the
# designated '__ptype' cannot be resolved. Defaults to `false`.
#
# @api public
def initialize(options = EMPTY_HASH)
@allow_unresolved = options[:allow_unresolved]
@allow_unresolved = false if @allow_unresolved.nil?
@loader = options[:loader]
@pcore_type_procs = {
PCORE_TYPE_HASH => proc do |hash, _|
value = hash[PCORE_VALUE_KEY]
build({}) do
top = value.size
idx = 0
while idx < top
key = without_value { convert(value[idx]) }
idx += 1
with(key) { convert(value[idx]) }
idx += 1
end
end
end,
PCORE_TYPE_SENSITIVE => proc do |hash, _|
build(Types::PSensitiveType::Sensitive.new(convert(hash[PCORE_VALUE_KEY])))
end,
PCORE_TYPE_DEFAULT => proc do |_, _|
build(:default)
end,
PCORE_TYPE_SYMBOL => proc do |hash, _|
build(:"#{hash[PCORE_VALUE_KEY]}")
end,
PCORE_LOCAL_REF_SYMBOL => proc do |hash, _|
build(JsonPath::Resolver.singleton.resolve(@root, hash[PCORE_VALUE_KEY]))
end
}
@pcore_type_procs.default = proc do |hash, type_value|
value = hash.include?(PCORE_VALUE_KEY) ? hash[PCORE_VALUE_KEY] : hash.reject { |key, _| PCORE_TYPE_KEY == key }
if type_value.is_a?(Hash)
type = without_value { convert(type_value) }
if type.is_a?(Hash)
raise SerializationError, _('Unable to deserialize type from %{type}') % { type: type } unless @allow_unresolved
hash
else
pcore_type_hash_to_value(type, value)
end
else
type = Types::TypeParser.singleton.parse(type_value, @loader)
if type.is_a?(Types::PTypeReferenceType)
unless @allow_unresolved
raise SerializationError, _('No implementation mapping found for Puppet Type %{type_name}') % { type_name: type_value }
end
hash
else
# not a string
pcore_type_hash_to_value(type, value)
end
end
end
end
# Converts the given `Data` _value_ and returns the resulting `RichData`
#
# @param value [Data] the value to convert
# @return [RichData] the processed result
#
# @api public
def convert(value)
case value
when Hash
pcore_type = value[PCORE_TYPE_KEY]
if pcore_type && (pcore_type.is_a?(String) || pcore_type.is_a?(Hash))
@pcore_type_procs[pcore_type].call(value, pcore_type)
else
build({}) { value.each_pair { |key, elem| with(key) { convert(elem) } } }
end
when Array
build([]) { value.each_with_index { |elem, idx| with(idx) { convert(elem) } } }
else
build(value)
end
end
private
def with(key)
parent_key = @key
@key = key
yield
@key = parent_key
end
def with_value(value)
@root = value unless instance_variable_defined?(:@root)
parent = @current
@current = value
yield
@current = parent
value
end
def without_value
parent = @current
@current = nil
value = yield
@current = parent
value
end
def build(value, &block)
vx = Builder.new(value)
@current[@key] = vx unless @current.nil?
with_value(vx, &block) if block_given?
vx.resolve
end
def build_object(builder, &block)
@current[@key] = builder unless @current.nil?
with_value(builder, &block) if block_given?
builder.resolve
end
def pcore_type_hash_to_value(pcore_type, value)
case value
when Hash
# Complex object
if value.empty?
build(pcore_type.create)
elsif pcore_type.implementation_class.respond_to?(:_pcore_init_from_hash)
build_object(ObjectHashBuilder.new(pcore_type.allocate)) { value.each_pair { |key, elem| with(key) { convert(elem) } } }
else
build_object(ObjectArrayBuilder.new(pcore_type.allocate)) { value.each_pair { |key, elem| with(key) { convert(elem) } } }
end
when String
build(pcore_type.create(value))
else
raise SerializationError, _('Cannot create a %{type_name} from a %{arg_class}') %
{ :type_name => pcore_type.name, :arg_class => value.class.name }
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/serialization/object.rb | lib/puppet/pops/serialization/object.rb | # frozen_string_literal: true
require_relative 'instance_reader'
require_relative 'instance_writer'
module Puppet::Pops
module Serialization
# Instance reader for objects that implement {Types::PuppetObject}
# @api private
class ObjectReader
include InstanceReader
def read(type, impl_class, value_count, deserializer)
(names, types, required_count) = type.parameter_info(impl_class)
max = names.size
unless value_count >= required_count && value_count <= max
raise Serialization::SerializationError, _("Feature count mismatch for %{value0}. Expected %{required_count} - %{max}, actual %{value_count}") % { value0: impl_class.name, required_count: required_count, max: max, value_count: value_count }
end
# Deserializer must know about this instance before we read its attributes
val = deserializer.remember(impl_class.allocate)
args = Array.new(value_count) { deserializer.read }
types.each_with_index do |ptype, index|
if index < args.size
arg = args[index]
Types::TypeAsserter.assert_instance_of(nil, ptype, arg) { "#{type.name}[#{names[index]}]" } unless arg == :default
else
attr = type[names[index]]
raise Serialization::SerializationError, _("Missing default value for %{type_name}[%{name}]") % { type_name: type.name, name: names[index] } unless attr && attr.value?
args << attr.value
end
end
val.send(:initialize, *args)
val
end
INSTANCE = ObjectReader.new
end
# Instance writer for objects that implement {Types::PuppetObject}
# @api private
class ObjectWriter
include InstanceWriter
def write(type, value, serializer)
impl_class = value.class
(names, _, required_count) = type.parameter_info(impl_class)
args = names.map { |name| value.send(name) }
# Pop optional arguments that are default
while args.size > required_count
break unless type[names[args.size - 1]].default_value?(args.last)
args.pop
end
if type.name.start_with?('Pcore::') || serializer.type_by_reference?
serializer.push_written(value)
serializer.start_pcore_object(type.name, args.size)
else
serializer.start_object(args.size + 1)
serializer.write(type)
serializer.push_written(value)
end
args.each { |arg| serializer.write(arg) }
end
INSTANCE = ObjectWriter.new
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/serialization/deserializer.rb | lib/puppet/pops/serialization/deserializer.rb | # frozen_string_literal: true
require_relative 'extension'
module Puppet::Pops
module Serialization
# The deserializer is capable of reading, arrays, maps, and complex objects using an underlying protocol reader. It takes care of
# resolving tabulations and assembling complex objects. The type of the complex objects are resolved using a loader.
# @api public
class Deserializer
# Provides access to the reader.
# @api private
attr_reader :reader, :loader
# @param [AbstractReader] reader the reader used when reading primitive objects from a stream
# @param [Loader::Loader] loader the loader used when resolving names of types
# @api public
def initialize(reader, loader)
@read = []
@reader = reader
@loader = loader
end
# Read the next value from the reader.
#
# @return [Object] the value that was read
# @api public
def read
val = @reader.read
case val
when Extension::Tabulation
@read[val.index]
when Extension::Default
:default
when Extension::ArrayStart
result = remember([])
val.size.times { result << read }
result
when Extension::MapStart
result = remember({})
val.size.times { key = read; result[key] = read }
result
when Extension::SensitiveStart
Types::PSensitiveType::Sensitive.new(read)
when Extension::PcoreObjectStart
type_name = val.type_name
type = Types::TypeParser.singleton.parse(type_name, @loader)
raise SerializationError, _("No implementation mapping found for Puppet Type %{type_name}") % { type_name: type_name } if type.is_a?(Types::PTypeReferenceType)
result = type.read(val.attribute_count, self)
if result.is_a?(Types::PObjectType)
existing_type = loader.load(:type, result.name)
if result.eql?(existing_type)
result = existing_type
else
# Add result to the loader unless it is equal to the existing_type. The add
# will only succeed when the existing_type is nil.
loader.add_entry(:type, result.name, result, nil)
end
end
result
when Extension::ObjectStart
type = read
type.read(val.attribute_count - 1, self)
when Numeric, String, true, false, nil
val
else
remember(val)
end
end
# Remember that a value has been read. This means that the value is given an index
# and that subsequent reads of a tabulation with that index should return the value.
# @param [Object] value The value to remember
# @return [Object] the argument
# @api private
def remember(value)
@read << value
value
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/serialization/to_stringified_converter.rb | lib/puppet/pops/serialization/to_stringified_converter.rb | # frozen_string_literal: true
module Puppet::Pops
module Serialization
# Class that can process an arbitrary object into a value that is assignable to `Data`
# and where contents is converted from rich data to one of:
# * Numeric (Integer, Float)
# * Boolean
# * Undef (nil)
# * String
# * Array
# * Hash
#
# The conversion is lossy - the result cannot be deserialized to produce the original data types.
# All rich values are transformed to strings..
# Hashes with rich keys are transformed to use string representation of such keys.
#
# @api public
class ToStringifiedConverter
include Evaluator::Runtime3Support
# Converts the given _value_ according to the given _options_ and return the result of the conversion
#
# @param value [Object] the value to convert
# @param options {Symbol => <Boolean,String>} options hash
# @option options [String] :message_prefix String to prepend to in warnings and errors
# @option options [String] :semantic object (AST) to pass to the issue reporter
# @return [Data] the processed result. An object assignable to `Data` with rich data stringified.
#
# @api public
def self.convert(value, options = EMPTY_HASH)
new(options).convert(value)
end
# Creates a new instance of the processor
#
# @param options {Symbol => Object} options hash
# @option options [String] :message_prefix String to prepend to path in warnings and errors
# @option semantic [Object] :semantic object to pass to the issue reporter
def initialize(options = EMPTY_HASH)
@message_prefix = options[:message_prefix]
@semantic = options[:semantic]
end
# Converts the given _value_
#
# @param value [Object] the value to convert
# @return [Data] the processed result. An object assignable to `Data` with rich data stringified.
#
# @api public
def convert(value)
@path = []
@values = {}
to_data(value)
end
private
def path_to_s
s = @message_prefix || ''
s << JsonPath.to_json_path(@path)[1..]
s
end
def to_data(value)
if value.instance_of?(String)
to_string_or_binary(value)
elsif value.nil? || Types::PScalarDataType::DEFAULT.instance?(value)
value
elsif :default == value
'default'
elsif value.is_a?(Symbol)
value.to_s
elsif value.instance_of?(Array)
process(value) do
result = []
value.each_with_index do |elem, index|
with(index) { result << to_data(elem) }
end
result
end
elsif value.instance_of?(Hash)
process(value) do
if value.keys.all? { |key| key.is_a?(String) && key != PCORE_TYPE_KEY && key != PCORE_VALUE_KEY }
result = {}
value.each_pair { |key, elem| with(key) { result[key] = to_data(elem) } }
result
else
non_string_keyed_hash_to_data(value)
end
end
else
unknown_to_string(value)
end
end
# Turns an ASCII-8BIT encoded string into a Binary, returns US_ASCII encoded and transforms all other strings to UTF-8
# with replacements for non Unicode characters.
# If String cannot be represented as UTF-8
def to_string_or_binary(value)
encoding = value.encoding
if encoding == Encoding::ASCII_8BIT
Puppet::Pops::Types::PBinaryType::Binary.from_binary_string(value).to_s
else
# Transform to UTF-8 (do not assume UTF-8 is correct) with source invalid byte
# sequences and UTF-8 undefined characters replaced by the default unicode uFFFD character
# (black diamond with question mark).
value.encode(Encoding::UTF_8, encoding, :invalid => :replace, :undef => :replace)
end
end
# Performs a check for endless recursion before
# it yields to the given block. The result of yielding is returned.
#
# @param value [Object] the value
# @yield The block that will produce the data for the value
# @return [Data] the result of yielding to the given block, or a hash denoting a reference
#
# @api private
def process(value, &block)
with_recursive_guard(value, &block)
end
# Pushes `key` to the end of the path and yields to the given block. The
# `key` is popped when the yield returns.
# @param key [Object] the key to push on the current path
# @yield The block that will produce the returned value
# @return [Object] the result of yielding to the given block
#
# @api private
def with(key)
@path.push(key)
value = yield
@path.pop
value
end
# @param value [Object] the value to use when checking endless recursion
# @yield The block that will produce the data
# @return [Data] the result of yielding to the given block
def with_recursive_guard(value)
id = value.object_id
if @recursive_lock
if @recursive_lock.include?(id)
serialization_issue(Issues::SERIALIZATION_ENDLESS_RECURSION, :type_name => value.class.name)
end
@recursive_lock[id] = true
else
@recursive_lock = { id => true }
end
v = yield
@recursive_lock.delete(id)
v
end
# A hash key that is non conforming
def unknown_key_to_string(value)
unknown_to_string(value)
end
def unknown_to_string(value)
if value.is_a?(Regexp)
return Puppet::Pops::Types::PRegexpType.regexp_to_s_with_delimiters(value)
elsif value.instance_of?(Types::PSensitiveType::Sensitive)
# to_s does not differentiate between instances - if they were used as keys in a hash
# the stringified result would override all Sensitive keys with the last such key's value
# this adds object_id.
#
return "#<#{value}:#{value.object_id}>"
elsif value.is_a?(Puppet::Pops::Types::PObjectType)
# regular to_s on an ObjectType gives the entire definition
return value.name
end
# Do a to_s on anything else
result = value.to_s
# The result may be ascii-8bit encoded without being a binary (low level object.inspect returns ascii-8bit string)
# This can be the case if runtime objects have very simple implementation (no to_s or inspect method).
# They are most likely not of Binary nature. Therefore the encoding is forced and only if it errors
# will the result be taken as binary and encoded as base64 string.
if result.encoding == Encoding::ASCII_8BIT
begin
result.force_encoding(Encoding::UTF_8)
rescue
# The result cannot be represented in UTF-8, make it a binary Base64 encoded string
Puppet::Pops::Types::PBinaryType::Binary.from_binary_string(result).to_s
end
end
result
end
def non_string_keyed_hash_to_data(hash)
result = {}
hash.each_pair do |key, value|
if key.is_a?(Symbol)
key = key.to_s
elsif !key.is_a?(String)
key = unknown_key_to_string(key)
end
if key == "__ptype" || key == "__pvalue"
key = "reserved key: #{key}"
end
with(key) { result[key] = to_data(value) }
end
result
end
def serialization_issue(issue, options = EMPTY_HASH)
semantic = @semantic
if semantic.nil?
tos = Puppet::Pops::PuppetStack.top_of_stack
if tos.empty?
semantic = Puppet::Pops::SemanticError.new(issue, nil, EMPTY_HASH)
else
file, line = stacktrace
semantic = Puppet::Pops::SemanticError.new(issue, nil, { :file => file, :line => line })
end
end
optionally_fail(issue, semantic, options)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/serialization/extension.rb | lib/puppet/pops/serialization/extension.rb | # frozen_string_literal: true
module Puppet::Pops
module Serialization
module Extension
# 0x00 - 0x0F are reserved for low-level serialization / tabulation extensions
# Tabulation internal to the low level protocol reader/writer
INNER_TABULATION = 0x00
# Tabulation managed by the serializer / deserializer
TABULATION = 0x01
# 0x10 - 0x1F are reserved for structural extensions
ARRAY_START = 0x10
MAP_START = 0x11
PCORE_OBJECT_START = 0x12
OBJECT_START = 0x13
SENSITIVE_START = 0x14
# 0x20 - 0x2f reserved for special extension objects
DEFAULT = 0x20
COMMENT = 0x21
# 0x30 - 0x7f reserved for mapping of specific runtime classes
REGEXP = 0x30
TYPE_REFERENCE = 0x31
SYMBOL = 0x32
TIME = 0x33
TIMESPAN = 0x34
VERSION = 0x35
VERSION_RANGE = 0x36
BINARY = 0x37
BASE64 = 0x38
URI = 0x39
# Marker module indicating whether or not an instance is tabulated or not
module NotTabulated; end
# Marker module for objects that starts a sequence, i.e. ArrayStart, MapStart, and PcoreObjectStart
module SequenceStart; end
# The class that triggers the use of the DEFAULT extension. It doesn't have any payload
class Default
include NotTabulated
INSTANCE = Default.new
end
# The class that triggers the use of the TABULATION extension. The payload is the tabulation index
class Tabulation
include NotTabulated
attr_reader :index
def initialize(index)
@index = index
end
end
# Tabulation internal to the protocol reader/writer
class InnerTabulation < Tabulation
end
# The class that triggers the use of the MAP_START extension. The payload is the map size (number of entries)
class MapStart
include NotTabulated
include SequenceStart
attr_reader :size
def initialize(size)
@size = size
end
# Sequence size is twice the map size since each entry is written as key and value
def sequence_size
@size * 2
end
end
# The class that triggers the use of the ARRAY_START extension. The payload is the array size
class ArrayStart
include NotTabulated
include SequenceStart
attr_reader :size
def initialize(size)
@size = size
end
def sequence_size
@size
end
end
# The class that triggers the use of the SENSITIVE_START extension. It has no payload
class SensitiveStart
include NotTabulated
INSTANCE = SensitiveStart.new
end
# The class that triggers the use of the PCORE_OBJECT_START extension. The payload is the name of the object type
# and the number of attributes in the instance.
class PcoreObjectStart
include SequenceStart
attr_reader :type_name, :attribute_count
def initialize(type_name, attribute_count)
@type_name = type_name
@attribute_count = attribute_count
end
def hash
@type_name.hash * 29 + attribute_count.hash
end
def eql?(o)
o.is_a?(PcoreObjectStart) && o.type_name == @type_name && o.attribute_count == @attribute_count
end
alias == eql?
def sequence_size
@attribute_count
end
end
class ObjectStart
include SequenceStart
attr_reader :attribute_count
def initialize(attribute_count)
@attribute_count = attribute_count
end
def hash
attribute_count.hash
end
def eql?(o)
o.is_a?(ObjectStart) && o.attribute_count == @attribute_count
end
alias == eql?
def sequence_size
@attribute_count
end
end
# The class that triggers the use of the COMMENT extension. The payload is comment text
class Comment
attr_reader :comment
def initialize(comment)
@comment = comment
end
def hash
@comment.hash
end
def eql?(o)
o.is_a?(Comment) && o.comment == @comment
end
alias == eql?
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/serialization/instance_reader.rb | lib/puppet/pops/serialization/instance_reader.rb | # frozen_string_literal: true
module Puppet::Pops
module Serialization
# An InstanceReader is responsible for reading an instance of a complex object using a deserializer. The read involves creating the
# instance, register it with the deserializer (so that self references can be resolved) and then read the instance data (which normally
# amounts to all attribute values).
# Instance readers are registered with of {Types::PObjectType}s to aid the type when reading instances.
#
# @api private
module InstanceReader
# @param [Class] impl_class the class of the instance to be created and initialized
# @param [Integer] value_count the expected number of objects that forms the initialization data
# @param [Deserializer] deserializer the deserializer to read from, and to register the instance with
# @return [Object] the instance that has been read
def read(impl_class, value_count, deserializer)
Serialization.not_implemented(self, 'read')
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/external/dot.rb | lib/puppet/external/dot.rb | # frozen_string_literal: true
# rdot.rb
#
#
# This is a modified version of dot.rb from Dave Thomas's rdoc project. I [Horst Duchene]
# renamed it to rdot.rb to avoid collision with an installed rdoc/dot.
#
# It also supports undirected edges.
module DOT
# These global vars are used to make nice graph source.
$tab = ' '
$tab2 = $tab * 2
# if we don't like 4 spaces, we can change it any time
def change_tab(t)
$tab = t
$tab2 = t * 2
end
# options for node declaration
NODE_OPTS = [
# attributes due to
# http://www.graphviz.org/Documentation/dotguide.pdf
# March, 26, 2005
'bottomlabel', # auxiliary label for nodes of shape M*
'color', # default: black; node shape color
'comment', # any string (format-dependent)
'distortion', # default: 0.0; node distortion for shape=polygon
'fillcolor', # default: lightgrey/black; node fill color
'fixedsize', # default: false; label text has no affect on node size
'fontcolor', # default: black; type face color
'fontname', # default: Times-Roman; font family
'fontsize', # default: 14; point size of label
'group', # name of node's group
'height', # default: .5; height in inches
'label', # default: node name; any string
'layer', # default: overlay range; all, id or id:id
'orientation', # default: 0.0; node rotation angle
'peripheries', # shape-dependent number of node boundaries
'regular', # default: false; force polygon to be regular
'shape', # default: ellipse; node shape; see Section 2.1 and Appendix E
'shapefile', # external EPSF or SVG custom shape file
'sides', # default: 4; number of sides for shape=polygon
'skew', # default: 0.0; skewing of node for shape=polygon
'style', # graphics options, e.g. bold, dotted, filled; cf. Section 2.3
'toplabel', # auxiliary label for nodes of shape M*
'URL', # URL associated with node (format-dependent)
'width', # default: .75; width in inches
'z', # default: 0.0; z coordinate for VRML output
# maintained for backward compatibility or rdot internal
'bgcolor',
'rank'
]
# options for edge declaration
EDGE_OPTS = [
'arrowhead', # default: normal; style of arrowhead at head end
'arrowsize', # default: 1.0; scaling factor for arrowheads
'arrowtail', # default: normal; style of arrowhead at tail end
'color', # default: black; edge stroke color
'comment', # any string (format-dependent)
'constraint', # default: true use edge to affect node ranking
'decorate', # if set, draws a line connecting labels with their edges
'dir', # default: forward; forward, back, both, or none
'fontcolor', # default: black type face color
'fontname', # default: Times-Roman; font family
'fontsize', # default: 14; point size of label
'headlabel', # label placed near head of edge
'headport', # n,ne,e,se,s,sw,w,nw
'headURL', # URL attached to head label if output format is ismap
'label', # edge label
'labelangle', # default: -25.0; angle in degrees which head or tail label is rotated off edge
'labeldistance', # default: 1.0; scaling factor for distance of head or tail label from node
'labelfloat', # default: false; lessen constraints on edge label placement
'labelfontcolor', # default: black; type face color for head and tail labels
'labelfontname', # default: Times-Roman; font family for head and tail labels
'labelfontsize', # default: 14 point size for head and tail labels
'layer', # default: overlay range; all, id or id:id
'lhead', # name of cluster to use as head of edge
'ltail', # name of cluster to use as tail of edge
'minlen', # default: 1 minimum rank distance between head and tail
'samehead', # tag for head node; edge heads with the same tag are merged onto the same port
'sametail', # tag for tail node; edge tails with the same tag are merged onto the same port
'style', # graphics options, e.g. bold, dotted, filled; cf. Section 2.3
'taillabel', # label placed near tail of edge
'tailport', # n,ne,e,se,s,sw,w,nw
'tailURL', # URL attached to tail label if output format is ismap
'weight', # default: 1; integer cost of stretching an edge
# maintained for backward compatibility or rdot internal
'id'
]
# options for graph declaration
GRAPH_OPTS = %w[
bgcolor
center clusterrank color concentrate
fontcolor fontname fontsize
label layerseq
margin mclimit
nodesep nslimit
ordering orientation
page
rank rankdir ranksep ratio
size
]
# a root class for any element in dot notation
class DOTSimpleElement
attr_accessor :name
def initialize(params = {})
@label = params['name'] || ''
end
def to_s
@name
end
end
# an element that has options ( node, edge, or graph )
class DOTElement < DOTSimpleElement
# attr_reader :parent
attr_accessor :name, :options
def initialize(params = {}, option_list = [])
super(params)
@name = params['name'] || nil
@parent = params['parent'] || nil
@options = {}
option_list.each { |i|
@options[i] = params[i] if params[i]
}
@options['label'] ||= @name if @name != 'node'
end
def each_option
@options.each { |i| yield i }
end
def each_option_pair
@options.each_pair { |key, val| yield key, val }
end
end
# This is used when we build nodes that have shape=record
# ports don't have options :)
class DOTPort < DOTSimpleElement
attr_accessor :label
def initialize(params = {})
super(params)
@name = params['label'] || ''
end
def to_s
(@name && @name != "" ? "<#{@name}>" : "") + @label.to_s
end
end
# node element
class DOTNode < DOTElement
def initialize(params = {}, option_list = NODE_OPTS)
super(params, option_list)
@ports = params['ports'] || []
end
def each_port
@ports.each { |i| yield i }
end
def <<(thing)
@ports << thing
end
def push(thing)
@ports.push(thing)
end
def pop
@ports.pop
end
def to_s(t = '')
# This code is totally incomprehensible; it needs to be replaced!
label = if @options['shape'] != 'record' && @ports.length == 0
if @options['label']
t + $tab + "label = #{stringify(@options['label'])}\n"
else
''
end
else
t + $tab + 'label = "' + " \\\n" +
t + $tab2 + "#{stringify(@options['label'])}| \\\n" +
@ports.collect { |i|
t + $tab2 + i.to_s
}.join("| \\\n") + " \\\n" +
t + $tab + '"' + "\n"
end
t + "#{@name} [\n" +
@options.to_a.filter_map { |i|
i[1] && i[0] != 'label' ?
t + $tab + "#{i[0]} = #{i[1]}" : nil
}.join(",\n") + (label != '' ? ",\n" : "\n") +
label +
t + "]\n"
end
private
def stringify(s)
%("#{s.gsub('"', '\\"')}")
end
end
# A subgraph element is the same to graph, but has another header in dot
# notation.
class DOTSubgraph < DOTElement
def initialize(params = {}, option_list = GRAPH_OPTS)
super(params, option_list)
@nodes = params['nodes'] || []
@dot_string = 'graph'
end
def each_node
@nodes.each { |i| yield i }
end
def <<(thing)
@nodes << thing
end
def push(thing)
@nodes.push(thing)
end
def pop
@nodes.pop
end
def to_s(t = '')
hdr = t + "#{@dot_string} #{@name} {\n"
options = @options.to_a.filter_map { |name, val|
if val && name != 'label'
t + $tab + "#{name} = #{val}"
else
name ? t + $tab + "#{name} = \"#{val}\"" : nil
end
}.join("\n") + "\n"
nodes = @nodes.collect { |i|
i.to_s(t + $tab)
}.join("\n") + "\n"
hdr + options + nodes + t + "}\n"
end
end
# This is a graph.
class DOTDigraph < DOTSubgraph
def initialize(params = {}, option_list = GRAPH_OPTS)
super(params, option_list)
@dot_string = 'digraph'
end
end
# This is an edge.
class DOTEdge < DOTElement
attr_accessor :from, :to
def initialize(params = {}, option_list = EDGE_OPTS)
super(params, option_list)
@from = params['from'] || nil
@to = params['to'] || nil
end
def edge_link
'--'
end
def to_s(t = '')
t + "#{@from} #{edge_link} #{to} [\n" +
@options.to_a.filter_map { |i|
if i[1] && i[0] != 'label'
t + $tab + "#{i[0]} = #{i[1]}"
else
i[1] ? t + $tab + "#{i[0]} = \"#{i[1]}\"" : nil
end
}.join("\n") + "\n#{t}]\n"
end
end
class DOTDirectedEdge < DOTEdge
def edge_link
'->'
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/agent.rb | lib/puppet/application/agent.rb | # frozen_string_literal: true
require_relative '../../puppet/application'
require_relative '../../puppet/daemon'
require_relative '../../puppet/util/pidlock'
require_relative '../../puppet/agent'
require_relative '../../puppet/configurer'
require_relative '../../puppet/ssl/oids'
class Puppet::Application::Agent < Puppet::Application
run_mode :agent
def app_defaults
super.merge({
:catalog_terminus => :rest,
:catalog_cache_terminus => :json,
:node_terminus => :rest,
:facts_terminus => :facter,
})
end
def preinit
# Do an initial trap, so that cancels don't get a stack trace.
Signal.trap(:INT) do
$stderr.puts _("Cancelling startup")
exit(0)
end
{
:waitforcert => nil,
:detailed_exitcodes => false,
:verbose => false,
:debug => false,
:setdest => false,
:enable => false,
:disable => false,
:fqdn => nil,
:serve => [],
:digest => 'SHA256',
:graph => true,
:fingerprint => false,
:sourceaddress => nil,
:start_time => Time.now,
}.each do |opt, val|
options[opt] = val
end
@argv = ARGV.dup
end
option("--disable [MESSAGE]") do |message|
options[:disable] = true
options[:disable_message] = message
end
option("--enable")
option("--debug", "-d")
option("--fqdn FQDN", "-f")
option("--test", "-t")
option("--verbose", "-v")
option("--fingerprint")
option("--digest DIGEST")
option("--sourceaddress IP_ADDRESS")
option("--detailed-exitcodes") do |_arg|
options[:detailed_exitcodes] = true
end
option("--logdest DEST", "-l DEST") do |arg|
handle_logdest_arg(arg)
end
option("--waitforcert WAITFORCERT", "-w") do |arg|
options[:waitforcert] = arg.to_i
end
option("--job-id ID") do |arg|
options[:job_id] = arg
end
def summary
_("The puppet agent daemon provided by OpenVox")
end
def help
<<~HELP
puppet-agent(8) -- #{summary}
========
SYNOPSIS
--------
Retrieves the client configuration from the OpenVox server and applies it to
the local host.
This service may be run as a daemon, run periodically using cron (or something
similar), or run interactively for testing purposes.
USAGE
-----
puppet agent [--certname <NAME>] [-D|--daemonize|--no-daemonize]
[-d|--debug] [--detailed-exitcodes] [--digest <DIGEST>] [--disable [MESSAGE]] [--enable]
[--fingerprint] [-h|--help] [-l|--logdest syslog|eventlog|<ABS FILEPATH>|console]
[--serverport <PORT>] [--noop] [-o|--onetime] [--sourceaddress <IP_ADDRESS>] [-t|--test]
[-v|--verbose] [-V|--version] [-w|--waitforcert <SECONDS>]
DESCRIPTION
-----------
This is the main puppet client. Its job is to retrieve the local
machine's configuration from a remote server and apply it. In order to
successfully communicate with the remote server, the client must have a
certificate signed by a certificate authority that the server trusts;
the recommended method for this, at the moment, is to run a certificate
authority as part of the puppet server (which is the default). The
client will connect and request a signed certificate, and will continue
connecting until it receives one.
Once the client has a signed certificate, it will retrieve its
configuration and apply it.
USAGE NOTES
-----------
'puppet agent' does its best to find a compromise between interactive
use and daemon use. If you run it with no arguments and no configuration, it
goes into the background, attempts to get a signed certificate, and retrieves
and applies its configuration every 30 minutes.
Some flags are meant specifically for interactive use --- in particular,
'test', 'tags' and 'fingerprint' are useful.
'--test' runs once in the foreground with verbose logging, then exits.
It also exits if it can't get a valid catalog. `--test` includes the
'--detailed-exitcodes' option by default and exits with one of the following
exit codes:
* 0: The run succeeded with no changes or failures; the system was already in
the desired state.
* 1: The run failed, or wasn't attempted due to another run already in progress.
* 2: The run succeeded, and some resources were changed.
* 4: The run succeeded, and some resources failed.
* 6: The run succeeded, and included both changes and failures.
'--tags' allows you to specify what portions of a configuration you want
to apply. Puppet elements are tagged with all of the class or definition
names that contain them, and you can use the 'tags' flag to specify one
of these names, causing only configuration elements contained within
that class or definition to be applied. This is very useful when you are
testing new configurations --- for instance, if you are just starting to
manage 'ntpd', you would put all of the new elements into an 'ntpd'
class, and call puppet with '--tags ntpd', which would only apply that
small portion of the configuration during your testing, rather than
applying the whole thing.
'--fingerprint' is a one-time flag. In this mode 'puppet agent' runs
once and displays on the console (and in the log) the current certificate
(or certificate request) fingerprint. Providing the '--digest' option
allows you to use a different digest algorithm to generate the fingerprint.
The main use is to verify that before signing a certificate request on
the master, the certificate request the master received is the same as
the one the client sent (to prevent against man-in-the-middle attacks
when signing certificates).
'--skip_tags' is a flag used to filter resources. If this is set, then
only resources not tagged with the specified tags will be applied.
Values must be comma-separated.
OPTIONS
-------
Note that any Puppet setting that's valid in the configuration file is also a
valid long argument. For example, 'server' is a valid setting, so you can
specify '--server <servername>' as an argument. Boolean settings accept a '--no-'
prefix to turn off a behavior, translating into '--setting' and '--no-setting'
pairs, such as `--daemonize` and `--no-daemonize`.
See the configuration file documentation at
https://puppet.com/docs/puppet/latest/configuration.html for the
full list of acceptable settings. A commented list of all settings can also be
generated by running puppet agent with '--genconfig'.
* --certname:
Set the certname (unique ID) of the client. The master reads this
unique identifying string, which is usually set to the node's
fully-qualified domain name, to determine which configurations the
node will receive. Use this option to debug setup problems or
implement unusual node identification schemes.
(This is a Puppet setting, and can go in puppet.conf.)
* --daemonize:
Send the process into the background. This is the default.
(This is a Puppet setting, and can go in puppet.conf. Note the special 'no-'
prefix for boolean settings on the command line.)
* --no-daemonize:
Do not send the process into the background.
(This is a Puppet setting, and can go in puppet.conf. Note the special 'no-'
prefix for boolean settings on the command line.)
* --debug:
Enable full debugging.
* --detailed-exitcodes:
Provide extra information about the run via exit codes; works only if '--test'
or '--onetime' is also specified. If enabled, 'puppet agent' uses the
following exit codes:
0: The run succeeded with no changes or failures; the system was already in
the desired state.
1: The run failed, or wasn't attempted due to another run already in progress.
2: The run succeeded, and some resources were changed.
4: The run succeeded, and some resources failed.
6: The run succeeded, and included both changes and failures.
* --digest:
Change the certificate fingerprinting digest algorithm. The default is
SHA256. Valid values depends on the version of OpenSSL installed, but
will likely contain MD5, MD2, SHA1 and SHA256.
* --disable:
Disable working on the local system. This puts a lock file in place,
causing 'puppet agent' not to work on the system until the lock file
is removed. This is useful if you are testing a configuration and do
not want the central configuration to override the local state until
everything is tested and committed.
Disable can also take an optional message that will be reported by the
'puppet agent' at the next disabled run.
'puppet agent' uses the same lock file while it is running, so no more
than one 'puppet agent' process is working at a time.
'puppet agent' exits after executing this.
* --enable:
Enable working on the local system. This removes any lock file,
causing 'puppet agent' to start managing the local system again
However, it continues to use its normal scheduling, so it might
not start for another half hour.
'puppet agent' exits after executing this.
* --evaltrace:
Logs each resource as it is being evaluated. This allows you to interactively
see exactly what is being done. (This is a Puppet setting, and can go in
puppet.conf. Note the special 'no-' prefix for boolean settings on the command line.)
* --fingerprint:
Display the current certificate or certificate signing request
fingerprint and then exit. Use the '--digest' option to change the
digest algorithm used.
* --help:
Print this help message
* --job-id:
Attach the specified job id to the catalog request and the report used for
this agent run. This option only works when '--onetime' is used. When using
Puppet Enterprise this flag should not be used as the orchestrator sets the
job-id for you and it must be unique.
* --logdest:
Where to send log messages. Choose between 'syslog' (the POSIX syslog
service), 'eventlog' (the Windows Event Log), 'console', or the path to a log
file. If debugging or verbosity is enabled, this defaults to 'console'.
Otherwise, it defaults to 'syslog' on POSIX systems and 'eventlog' on Windows.
Multiple destinations can be set using a comma separated list
(eg: `/path/file1,console,/path/file2`)"
A path ending with '.json' will receive structured output in JSON format. The
log file will not have an ending ']' automatically written to it due to the
appending nature of logging. It must be appended manually to make the content
valid JSON.
A path ending with '.jsonl' will receive structured output in JSON Lines
format.
* --masterport:
The port on which to contact the Puppet Server.
(This is a Puppet setting, and can go in puppet.conf.
Deprecated in favor of the 'serverport' setting.)
* --noop:
Use 'noop' mode where the daemon runs in a no-op or dry-run mode. This
is useful for seeing what changes Puppet would make without actually
executing the changes.
(This is a Puppet setting, and can go in puppet.conf. Note the special 'no-'
prefix for boolean settings on the command line.)
* --onetime:
Run the configuration once. Runs a single (normally daemonized) Puppet
run. Useful for interactively running puppet agent when used in
conjunction with the --no-daemonize option.
(This is a Puppet setting, and can go in puppet.conf. Note the special 'no-'
prefix for boolean settings on the command line.)
* --serverport:
The port on which to contact the Puppet Server.
(This is a Puppet setting, and can go in puppet.conf.)
* --sourceaddress:
Set the source IP address for transactions. This defaults to automatically selected.
(This is a Puppet setting, and can go in puppet.conf.)
* --test:
Enable the most common options used for testing. These are 'onetime',
'verbose', 'no-daemonize', 'no-usecacheonfailure', 'detailed-exitcodes',
'no-splay', and 'show_diff'.
* --trace
Prints stack traces on some errors. (This is a Puppet setting, and can go in
puppet.conf. Note the special 'no-' prefix for boolean settings on the command line.)
* --verbose:
Turn on verbose reporting.
* --version:
Print the puppet version number and exit.
* --waitforcert:
This option only matters for daemons that do not yet have certificates
and it is enabled by default, with a value of 120 (seconds). This
causes 'puppet agent' to connect to the server every 2 minutes and ask
it to sign a certificate request. This is useful for the initial setup
of a puppet client. You can turn off waiting for certificates by
specifying a time of 0.
(This is a Puppet setting, and can go in puppet.conf.)
* --write_catalog_summary
After compiling the catalog saves the resource list and classes list to the node
in the state directory named classes.txt and resources.txt
(This is a Puppet setting, and can go in puppet.conf.)
EXAMPLE
-------
$ puppet agent --server puppet.domain.com
DIAGNOSTICS
-----------
Puppet agent accepts the following signals:
* SIGHUP:
Restart the puppet agent daemon.
* SIGINT and SIGTERM:
Shut down the puppet agent daemon.
* SIGUSR1:
Immediately retrieve and apply configurations from the puppet master.
* SIGUSR2:
Close file descriptors for log files and reopen them. Used with logrotate.
AUTHOR
------
Luke Kanies
COPYRIGHT
---------
Copyright (c) 2011 Puppet Inc.
Copyright (c) 2024 Vox Pupuli
Licensed under the Apache 2.0 License
HELP
end
def run_command
if options[:fingerprint]
fingerprint
else
# It'd be nice to daemonize later, but we have to daemonize before
# waiting for certificates so that we don't block
daemon = daemonize_process_when(Puppet[:daemonize])
# Setup signal traps immediately after daemonization so we clean up the daemon
daemon.set_signal_traps
log_config if Puppet[:daemonize]
# Each application is responsible for pushing loaders onto the context.
# Use the current environment that has already been established, though
# it may change later during the configurer run.
env = Puppet.lookup(:current_environment)
Puppet.override(current_environment: env,
loaders: Puppet::Pops::Loaders.new(env, true)) do
if Puppet[:onetime]
onetime(daemon)
else
main(daemon)
end
end
end
end
def log_config
# skip also config reading and parsing if debug is not enabled
return unless Puppet::Util::Log.sendlevel?(:debug)
Puppet.settings.stringify_settings(:agent, :all).each_pair do |k, v|
next if k.include?("password") || v.to_s.empty?
Puppet.debug("Using setting: #{k}=#{v}")
end
end
def fingerprint
Puppet::Util::Log.newdestination(:console)
cert_provider = Puppet::X509::CertProvider.new
client_cert = cert_provider.load_client_cert(Puppet[:certname])
if client_cert
puts Puppet::SSL::Digest.new(options[:digest].to_s, client_cert.to_der).to_s
else
csr = cert_provider.load_request(Puppet[:certname])
if csr
puts Puppet::SSL::Digest.new(options[:digest].to_s, csr.to_der).to_s
else
$stderr.puts _("Fingerprint asked but neither the certificate, nor the certificate request have been issued")
exit(1)
end
end
rescue => e
Puppet.log_exception(e, _("Failed to generate fingerprint: %{message}") % { message: e.message })
exit(1)
end
def onetime(daemon)
begin
exitstatus = daemon.agent.run({ :job_id => options[:job_id], :start_time => options[:start_time], :waitforcert => options[:waitforcert] })
rescue => detail
Puppet.log_exception(detail)
end
daemon.stop(:exit => false)
if !exitstatus
exit(1)
elsif options[:detailed_exitcodes] then
exit(exitstatus)
else
exit(0)
end
end
def main(daemon)
Puppet.notice _("Starting Puppet client version %{version}") % { version: Puppet.version }
daemon.start
end
# Enable all of the most common test options.
def setup_test
Puppet.settings.handlearg("--no-usecacheonfailure")
Puppet.settings.handlearg("--no-splay")
Puppet.settings.handlearg("--show_diff")
Puppet.settings.handlearg("--no-daemonize")
options[:verbose] = true
Puppet[:onetime] = true
options[:detailed_exitcodes] = true
end
def setup
raise ArgumentError, _("The puppet agent command does not take parameters") unless command_line.args.empty?
setup_test if options[:test]
setup_logs
exit(Puppet.settings.print_configs ? 0 : 1) if Puppet.settings.print_configs?
Puppet::SSL::Oids.register_puppet_oids
if options[:fqdn]
Puppet[:certname] = options[:fqdn]
end
Puppet.settings.use :main, :agent, :ssl
Puppet::Transaction::Report.indirection.terminus_class = :rest
# we want the last report to be persisted locally
Puppet::Transaction::Report.indirection.cache_class = :yaml
if Puppet[:catalog_cache_terminus]
Puppet::Resource::Catalog.indirection.cache_class = Puppet[:catalog_cache_terminus]
end
# In fingerprint mode we don't need to set up the whole agent
unless options[:fingerprint]
setup_agent
end
end
private
def enable_disable_client(agent)
if options[:enable]
agent.enable
elsif options[:disable]
agent.disable(options[:disable_message] || 'reason not specified')
end
exit(0)
end
def setup_agent
agent = Puppet::Agent.new(Puppet::Configurer, !(Puppet[:onetime]))
enable_disable_client(agent) if options[:enable] or options[:disable]
@agent = agent
end
def daemonize_process_when(should_daemonize)
daemon = Puppet::Daemon.new(@agent, Puppet::Util::Pidlock.new(Puppet[:pidfile]))
daemon.argv = @argv
daemon.daemonize if should_daemonize
daemon
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/resource.rb | lib/puppet/application/resource.rb | # frozen_string_literal: true
require_relative '../../puppet/application'
class Puppet::Application::Resource < Puppet::Application
environment_mode :not_required
attr_accessor :host, :extra_params
def preinit
@extra_params = [:provider]
end
option("--debug", "-d")
option("--verbose", "-v")
option("--edit", "-e")
option("--to_yaml", "-y")
option('--fail', '-f')
option("--types", "-t") do |_arg|
env = Puppet.lookup(:environments).get(Puppet[:environment]) || create_default_environment
types = []
Puppet::Type.typeloader.loadall(env)
Puppet::Type.eachtype do |t|
next if t.name == :component
types << t.name.to_s
end
puts types.sort
exit(0)
end
option("--param PARAM", "-p") do |arg|
@extra_params << arg.to_sym
end
def summary
_("The OpenVox resource abstraction layer shell")
end
def help
<<~HELP
puppet-resource(8) -- #{summary}
========
SYNOPSIS
--------
Uses the OpenVox RAL to directly interact with the system.
USAGE
-----
puppet resource [-h|--help] [-d|--debug] [-v|--verbose] [-e|--edit]
[-p|--param <parameter>] [-t|--types] [-y|--to_yaml] <type>
[<name>] [<attribute>=<value> ...]
DESCRIPTION
-----------
This command provides simple facilities for converting current system
state into Puppet code, along with some ability to modify the current
state using Puppet's RAL.
By default, you must at least provide a type to list, in which case
puppet resource will tell you everything it knows about all resources of
that type. You can optionally specify an instance name, and puppet
resource will only describe that single instance.
If given a type, a name, and a series of <attribute>=<value> pairs,
puppet resource will modify the state of the specified resource.
Alternately, if given a type, a name, and the '--edit' flag, puppet
resource will write its output to a file, open that file in an editor,
and then apply the saved file as a Puppet transaction.
OPTIONS
-------
Note that any setting that's valid in the configuration
file is also a valid long argument. For example, 'ssldir' is a valid
setting, so you can specify '--ssldir <directory>' as an
argument.
See the configuration file documentation at
https://puppet.com/docs/puppet/latest/configuration.html for the
full list of acceptable parameters. A commented list of all
configuration options can also be generated by running puppet with
'--genconfig'.
* --debug:
Enable full debugging.
* --edit:
Write the results of the query to a file, open the file in an editor,
and read the file back in as an executable Puppet manifest.
* --help:
Print this help message.
* --param:
Add more parameters to be outputted from queries.
* --types:
List all available types.
* --verbose:
Print extra information.
* --to_yaml:
Output found resources in yaml format, suitable to use with Hiera and
create_resources.
* --fail:
Fails and returns an exit code of 1 if the resource could not be modified.
EXAMPLE
-------
This example uses `puppet resource` to return a Puppet configuration for
the user `luke`:
$ puppet resource user luke
user { 'luke':
home => '/home/luke',
uid => '100',
ensure => 'present',
comment => 'Luke Kanies,,,',
gid => '1000',
shell => '/bin/bash',
groups => ['sysadmin','audio','video','puppet']
}
AUTHOR
------
Luke Kanies
COPYRIGHT
---------
Copyright (c) 2011 Puppet Inc.
Copyright (c) 2024 Vox Pupuli
Licensed under the Apache 2.0 License
HELP
end
def main
# If the specified environment does not exist locally, fall back to the default (production) environment
env = Puppet.lookup(:environments).get(Puppet[:environment]) || create_default_environment
Puppet.override(
current_environment: env,
loaders: Puppet::Pops::Loaders.new(env),
stringify_rich: true
) do
type, name, params = parse_args(command_line.args)
raise _("Editing with Yaml output is not supported") if options[:edit] and options[:to_yaml]
resources = find_or_save_resources(type, name, params)
if options[:to_yaml]
data = resources.map do |resource|
resource.prune_parameters(:parameters_to_include => @extra_params).to_hiera_hash
end.inject(:merge!)
text = YAML.dump(type.downcase => data)
else
text = resources.map do |resource|
resource.prune_parameters(:parameters_to_include => @extra_params).to_manifest.force_encoding(Encoding.default_external)
end.join("\n")
end
options[:edit] ?
handle_editing(text) :
(puts text)
end
end
def setup
Puppet::Util::Log.newdestination(:console)
set_log_level
end
private
def local_key(type, name)
[type, name].join('/')
end
def handle_editing(text)
require 'tempfile'
# Prefer the current directory, which is more likely to be secure
# and, in the case of interactive use, accessible to the user.
tmpfile = Tempfile.new('x2puppet', Dir.pwd, :encoding => Encoding::UTF_8)
begin
# sync write, so nothing buffers before we invoke the editor.
tmpfile.sync = true
tmpfile.puts text
# edit the content
system(ENV.fetch("EDITOR", nil) || 'vi', tmpfile.path)
# ...and, now, pass that file to puppet to apply. Because
# many editors rename or replace the original file we need to
# feed the pathname, not the file content itself, to puppet.
system('puppet apply -v ' + tmpfile.path)
ensure
# The temporary file will be safely removed.
tmpfile.close(true)
end
end
def parse_args(args)
type = args.shift or raise _("You must specify the type to display")
Puppet::Type.type(type) or raise _("Could not find type %{type}") % { type: type }
name = args.shift
params = {}
args.each do |setting|
if setting =~ /^(\w+)=(.+)$/
params[::Regexp.last_match(1)] = ::Regexp.last_match(2)
else
raise _("Invalid parameter setting %{setting}") % { setting: setting }
end
end
[type, name, params]
end
def create_default_environment
Puppet.debug("Specified environment '#{Puppet[:environment]}' does not exist on the filesystem, defaulting to 'production'")
Puppet[:environment] = :production
basemodulepath = Puppet::Node::Environment.split_path(Puppet[:basemodulepath])
modulepath = Puppet[:modulepath]
modulepath = (modulepath.nil? || modulepath.empty?) ? basemodulepath : Puppet::Node::Environment.split_path(modulepath)
Puppet::Node::Environment.create(Puppet[:environment], modulepath, Puppet::Node::Environment::NO_MANIFEST)
end
def find_or_save_resources(type, name, params)
key = local_key(type, name)
Puppet.override(stringify_rich: true) do
if name
if params.empty?
[Puppet::Resource.indirection.find(key)]
else
resource = Puppet::Resource.new(type, name, :parameters => params)
# save returns [resource that was saved, transaction log from applying the resource]
save_result, report = Puppet::Resource.indirection.save(resource, key)
status = report.resource_statuses[resource.ref]
raise "Failed to manage resource #{resource.ref}" if status&.failed? && options[:fail]
[save_result]
end
else
if type == "file"
raise _("Listing all file instances is not supported. Please specify a file or directory, e.g. puppet resource file /etc")
end
Puppet::Resource.indirection.search(key, {})
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/report.rb | lib/puppet/application/report.rb | # frozen_string_literal: true
require_relative '../../puppet/application/indirection_base'
class Puppet::Application::Report < Puppet::Application::IndirectionBase
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/script.rb | lib/puppet/application/script.rb | # frozen_string_literal: true
require_relative '../../puppet/application'
require_relative '../../puppet/configurer'
require_relative '../../puppet/util/profiler/aggregate'
require_relative '../../puppet/parser/script_compiler'
class Puppet::Application::Script < Puppet::Application
option("--debug", "-d")
option("--execute EXECUTE", "-e") do |arg|
options[:code] = arg
end
option("--test", "-t")
option("--verbose", "-v")
option("--logdest LOGDEST", "-l") do |arg|
handle_logdest_arg(arg)
end
def summary
_("Run a puppet manifests as a script without compiling a catalog")
end
def help
<<~HELP
puppet-script(8) -- #{summary}
========
SYNOPSIS
--------
Runs a puppet language script without compiling a catalog.
USAGE
-----
puppet script [-h|--help] [-V|--version] [-d|--debug] [-v|--verbose]
[-e|--execute]
[-l|--logdest syslog|eventlog|<FILE>|console] [--noop]
<file>
DESCRIPTION
-----------
This is a standalone puppet script runner tool; use it to run puppet code
without compiling a catalog.
When provided with a modulepath, via command line or config file, puppet
script can load functions, types, tasks and plans from modules.
OPTIONS
-------
Note that any setting that's valid in the configuration
file is also a valid long argument. For example, 'environment' is a
valid setting, so you can specify '--environment mytest'
as an argument.
See the configuration file documentation at
https://puppet.com/docs/puppet/latest/configuration.html for the
full list of acceptable parameters. A commented list of all
configuration options can also be generated by running puppet with
'--genconfig'.
* --debug:
Enable full debugging.
* --help:
Print this help message
* --logdest:
Where to send log messages. Choose between 'syslog' (the POSIX syslog
service), 'eventlog' (the Windows Event Log), 'console', or the path to a log
file. Defaults to 'console'.
Multiple destinations can be set using a comma separated list
(eg: `/path/file1,console,/path/file2`)"
A path ending with '.json' will receive structured output in JSON format. The
log file will not have an ending ']' automatically written to it due to the
appending nature of logging. It must be appended manually to make the content
valid JSON.
A path ending with '.jsonl' will receive structured output in JSON Lines
format.
* --noop:
Use 'noop' mode where Puppet runs in a no-op or dry-run mode. This
is useful for seeing what changes Puppet will make without actually
executing the changes. Applies to tasks only.
* --execute:
Execute a specific piece of Puppet code
* --verbose:
Print extra information.
EXAMPLE
-------
$ puppet script -l /tmp/manifest.log manifest.pp
$ puppet script --modulepath=/root/dev/modules -e 'notice("hello world")'
AUTHOR
------
Henrik Lindberg
COPYRIGHT
---------
Copyright (c) 2017 Puppet Inc.
Copyright (c) 2024 Vox Pupuli
Licensed under the Apache 2.0 License
HELP
end
def app_defaults
super.merge({
:default_file_terminus => :file_server,
})
end
def run_command
if Puppet.features.bolt?
Puppet.override(:bolt_executor => Bolt::Executor.new) do
main
end
else
raise _("Bolt must be installed to use the script application")
end
end
def main
# The tasks feature is always on
Puppet[:tasks] = true
# Set the puppet code or file to use.
if options[:code] || command_line.args.length == 0
Puppet[:code] = options[:code] || STDIN.read
else
manifest = command_line.args.shift
raise _("Could not find file %{manifest}") % { manifest: manifest } unless Puppet::FileSystem.exist?(manifest)
Puppet.warning(_("Only one file can be used per run. Skipping %{files}") % { files: command_line.args.join(', ') }) if command_line.args.size > 0
end
unless Puppet[:node_name_fact].empty?
# Collect the facts specified for that node
facts = Puppet::Node::Facts.indirection.find(Puppet[:node_name_value])
raise _("Could not find facts for %{node}") % { node: Puppet[:node_name_value] } unless facts
Puppet[:node_name_value] = facts.values[Puppet[:node_name_fact]]
facts.name = Puppet[:node_name_value]
end
# Find the Node
node = Puppet::Node.indirection.find(Puppet[:node_name_value])
raise _("Could not find node %{node}") % { node: Puppet[:node_name_value] } unless node
configured_environment = node.environment || Puppet.lookup(:current_environment)
apply_environment = manifest ?
configured_environment.override_with(:manifest => manifest) :
configured_environment
# Modify the node descriptor to use the special apply_environment.
# It is based on the actual environment from the node, or the locally
# configured environment if the node does not specify one.
# If a manifest file is passed on the command line, it overrides
# the :manifest setting of the apply_environment.
node.environment = apply_environment
# TRANSLATION, the string "For puppet script" is not user facing
Puppet.override({ :current_environment => apply_environment }, "For puppet script") do
# Merge in the facts.
node.merge(facts.values) if facts
# Add server facts so $server_facts[environment] exists when doing a puppet script
# SCRIPT TODO: May be needed when running scripts under orchestrator. Leave it for now.
#
node.add_server_facts({})
begin
# Compile the catalog
# When compiling, the compiler traps and logs certain errors
# Those that do not lead to an immediate exit are caught by the general
# rule and gets logged.
#
begin
# support the following features when evaluating puppet code
# * $facts with facts from host running the script
# * $settings with 'settings::*' namespace populated, and '$settings::all_local' hash
# * $trusted as setup when using puppet apply
# * an environment
#
# fixup trusted information
node.sanitize()
compiler = Puppet::Parser::ScriptCompiler.new(node.environment, node.name)
topscope = compiler.topscope
# When scripting the trusted data are always local, but set them anyway
topscope.set_trusted(node.trusted_data)
# Server facts are always about the local node's version etc.
topscope.set_server_facts(node.server_facts)
# Set $facts for the node running the script
facts_hash = node.facts.nil? ? {} : node.facts.values
topscope.set_facts(facts_hash)
# create the $settings:: variables
topscope.merge_settings(node.environment.name, false)
compiler.compile()
rescue Puppet::Error
# already logged and handled by the compiler, including Puppet::ParseErrorWithIssue
exit(1)
end
exit(0)
rescue => detail
Puppet.log_exception(detail)
exit(1)
end
end
ensure
if @profiler
Puppet::Util::Profiler.remove_profiler(@profiler)
@profiler.shutdown
end
end
def setup
exit(Puppet.settings.print_configs ? 0 : 1) if Puppet.settings.print_configs?
handle_logdest_arg(Puppet[:logdest])
Puppet::Util::Log.newdestination(:console) unless options[:setdest]
Signal.trap(:INT) do
$stderr.puts _("Exiting")
exit(1)
end
# TODO: This skips applying the settings catalog for these settings, but
# the effect of doing this is unknown. It may be that it only works if there is a puppet
# installed where a settings catalog have already been applied...
# This saves 1/5th of the startup time
# Puppet.settings.use :main, :agent, :ssl
# When running a script, the catalog is not relevant, and neither is caching of it
Puppet::Resource::Catalog.indirection.cache_class = nil
# we do not want the last report to be persisted
Puppet::Transaction::Report.indirection.cache_class = nil
set_log_level
if Puppet[:profile]
@profiler = Puppet::Util::Profiler.add_profiler(Puppet::Util::Profiler::Aggregate.new(Puppet.method(:info), "script"))
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/generate.rb | lib/puppet/application/generate.rb | # frozen_string_literal: true
require_relative '../../puppet/application/face_base'
# The Generate application.
class Puppet::Application::Generate < Puppet::Application::FaceBase
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/doc.rb | lib/puppet/application/doc.rb | # frozen_string_literal: true
require_relative '../../puppet/application'
class Puppet::Application::Doc < Puppet::Application
run_mode :server
attr_accessor :unknown_args, :manifest
def preinit
{ :references => [], :mode => :text, :format => :to_markdown }.each do |name, value|
options[name] = value
end
@unknown_args = []
@manifest = false
end
option("--all", "-a")
option("--outputdir OUTPUTDIR", "-o")
option("--verbose", "-v")
option("--debug", "-d")
option("--charset CHARSET")
option("--format FORMAT", "-f") do |arg|
method = "to_#{arg}"
require_relative '../../puppet/util/reference'
if Puppet::Util::Reference.method_defined?(method)
options[:format] = method
else
raise _("Invalid output format %{arg}") % { arg: arg }
end
end
option("--mode MODE", "-m") do |arg|
require_relative '../../puppet/util/reference'
if Puppet::Util::Reference.modes.include?(arg) or arg.intern == :rdoc
options[:mode] = arg.intern
else
raise _("Invalid output mode %{arg}") % { arg: arg }
end
end
option("--list", "-l") do |_arg|
require_relative '../../puppet/util/reference'
refs = Puppet::Util::Reference.references(Puppet.lookup(:current_environment))
puts refs.collect { |r| Puppet::Util::Reference.reference(r).doc }.join("\n")
exit(0)
end
option("--reference REFERENCE", "-r") do |arg|
options[:references] << arg.intern
end
def summary
_("Generate Puppet references for OpenVox")
end
def help
<<~HELP
puppet-doc(8) -- #{summary}
========
SYNOPSIS
--------
Generates a reference for all Puppet types. Largely meant for internal use. (Deprecated)
USAGE
-----
puppet doc [-h|--help] [-l|--list]
[-r|--reference <reference-name>]
DESCRIPTION
-----------
This deprecated command generates a Markdown document to stdout
describing all installed Puppet types or all allowable arguments to
puppet executables. It is largely meant for internal use and is used to
generate the reference documents which can be posted to a website.
For Puppet module documentation (and all other use cases) this command
has been superseded by the "puppet-strings"
module - see https://github.com/puppetlabs/puppetlabs-strings for more information.
This command (puppet-doc) will be removed once the
puppetlabs internal documentation processing pipeline is completely based
on puppet-strings.
OPTIONS
-------
* --help:
Print this help message
* --reference:
Build a particular reference. Get a list of references by running
'puppet doc --list'.
EXAMPLE
-------
$ puppet doc -r type > /tmp/type_reference.markdown
AUTHOR
------
Luke Kanies
COPYRIGHT
---------
Copyright (c) 2011 Puppet Inc.
Copyright (c) 2024 Vox Pupuli
Licensed under the Apache 2.0 License
HELP
end
def handle_unknown(opt, arg)
@unknown_args << { :opt => opt, :arg => arg }
true
end
def run_command
[:rdoc].include?(options[:mode]) ? send(options[:mode]) : other
end
def rdoc
exit_code = 0
files = []
unless @manifest
env = Puppet.lookup(:current_environment)
files += env.modulepath
files << ::File.dirname(env.manifest) if env.manifest != Puppet::Node::Environment::NO_MANIFEST
end
files += command_line.args
Puppet.info _("scanning: %{files}") % { files: files.inspect }
Puppet.settings[:document_all] = options[:all] || false
begin
require_relative '../../puppet/util/rdoc'
if @manifest
Puppet::Util::RDoc.manifestdoc(files)
else
options[:outputdir] = "doc" unless options[:outputdir]
Puppet::Util::RDoc.rdoc(options[:outputdir], files, options[:charset])
end
rescue => detail
Puppet.log_exception(detail, _("Could not generate documentation: %{detail}") % { detail: detail })
exit_code = 1
end
exit exit_code
end
def other
text = ''.dup
with_contents = options[:references].length <= 1
exit_code = 0
require_relative '../../puppet/util/reference'
options[:references].sort_by(&:to_s).each do |name|
section = Puppet::Util::Reference.reference(name)
raise _("Could not find reference %{name}") % { name: name } unless section
begin
# Add the per-section text, but with no ToC
text += section.send(options[:format], with_contents)
rescue => detail
Puppet.log_exception(detail, _("Could not generate reference %{name}: %{detail}") % { name: name, detail: detail })
exit_code = 1
next
end
end
text += Puppet::Util::Reference.footer unless with_contents # We've only got one reference
puts text
exit exit_code
end
def setup
# sole manifest documentation
if command_line.args.size > 0
options[:mode] = :rdoc
@manifest = true
end
if options[:mode] == :rdoc
setup_rdoc
else
setup_reference
end
setup_logging
end
def setup_reference
if options[:all]
# Don't add dynamic references to the "all" list.
require_relative '../../puppet/util/reference'
refs = Puppet::Util::Reference.references(Puppet.lookup(:current_environment))
options[:references] = refs.reject do |ref|
Puppet::Util::Reference.reference(ref).dynamic?
end
end
options[:references] << :type if options[:references].empty?
end
def setup_rdoc
# consume the unknown options
# and feed them as settings
if @unknown_args.size > 0
@unknown_args.each do |option|
# force absolute path for modulepath when passed on commandline
if option[:opt] == "--modulepath"
option[:arg] = option[:arg].split(::File::PATH_SEPARATOR).collect { |p| ::File.expand_path(p) }.join(::File::PATH_SEPARATOR)
end
Puppet.settings.handlearg(option[:opt], option[:arg])
end
end
end
def setup_logging
Puppet::Util::Log.level = :warning
set_log_level
Puppet::Util::Log.newdestination(:console)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/node.rb | lib/puppet/application/node.rb | # frozen_string_literal: true
require_relative '../../puppet/application/indirection_base'
class Puppet::Application::Node < Puppet::Application::IndirectionBase
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/ssl.rb | lib/puppet/application/ssl.rb | # frozen_string_literal: true
require_relative '../../puppet/application'
require_relative '../../puppet/ssl/oids'
class Puppet::Application::Ssl < Puppet::Application
run_mode :agent
def summary
_("Manage SSL keys and certificates for OpenVox SSL clients")
end
def help
<<~HELP
puppet-ssl(8) -- #{summary}
========
SYNOPSIS
--------
Manage SSL keys and certificates for clients needing
to communicate with an OpenVox infrastructure.
USAGE
-----
puppet ssl <action> [-h|--help] [-v|--verbose] [-d|--debug] [--localca] [--target CERTNAME]
OPTIONS
-------
* --help:
Print this help message.
* --verbose:
Print extra information.
* --debug:
Enable full debugging.
* --localca
Also clean the local CA certificate and CRL.
* --target CERTNAME
Clean the specified device certificate instead of this host's certificate.
ACTIONS
-------
* bootstrap:
Perform all of the steps necessary to request and download a client
certificate. If autosigning is disabled, then puppet will wait every
`waitforcert` seconds for its certificate to be signed. To only attempt
once and never wait, specify a time of 0. Since `waitforcert` is a
Puppet setting, it can be specified as a time interval, such as 30s,
5m, 1h.
* submit_request:
Generate a certificate signing request (CSR) and submit it to the CA. If
a private and public key pair already exist, they will be used to generate
the CSR. Otherwise, a new key pair will be generated. If a CSR has already
been submitted with the given `certname`, then the operation will fail.
* generate_request:
Generate a certificate signing request (CSR). If a private and public key
pair exist, they will be used to generate the CSR. Otherwise a new key
pair will be generated.
* download_cert:
Download a certificate for this host. If the current private key matches
the downloaded certificate, then the certificate will be saved and used
for subsequent requests. If there is already an existing certificate, it
will be overwritten.
* verify:
Verify the private key and certificate are present and match, verify the
certificate is issued by a trusted CA, and check revocation status.
* clean:
Remove the private key and certificate related files for this host. If
`--localca` is specified, then also remove this host's local copy of the
CA certificate(s) and CRL bundle. if `--target CERTNAME` is specified, then
remove the files for the specified device on this host instead of this host.
* show:
Print the full-text version of this host's certificate.
COPYRIGHT
---------
Copyright (c) 2011 Puppet Inc.
Copyright (c) 2024 Vox Pupuli
Licensed under the Apache 2.0 License
HELP
end
option('--target CERTNAME') do |arg|
options[:target] = arg.to_s
end
option('--localca')
option('--verbose', '-v')
option('--debug', '-d')
def initialize(command_line = Puppet::Util::CommandLine.new)
super(command_line)
@cert_provider = Puppet::X509::CertProvider.new
@ssl_provider = Puppet::SSL::SSLProvider.new
@machine = Puppet::SSL::StateMachine.new
@session = Puppet.runtime[:http].create_session
end
def setup_logs
set_log_level(options)
Puppet::Util::Log.newdestination(:console)
end
def main
if command_line.args.empty?
raise Puppet::Error, _("An action must be specified.")
end
if options[:target]
# Override the following, as per lib/puppet/application/device.rb
Puppet[:certname] = options[:target]
Puppet[:confdir] = File.join(Puppet[:devicedir], Puppet[:certname])
Puppet[:vardir] = File.join(Puppet[:devicedir], Puppet[:certname])
Puppet.settings.use(:main, :agent, :device)
else
Puppet.settings.use(:main, :agent)
end
Puppet::SSL::Oids.register_puppet_oids
Puppet::SSL::Oids.load_custom_oid_file(Puppet[:trusted_oid_mapping_file])
certname = Puppet[:certname]
action = command_line.args.first
case action
when 'submit_request'
ssl_context = @machine.ensure_ca_certificates
if submit_request(ssl_context)
cert = download_cert(ssl_context)
unless cert
Puppet.info(_("The certificate for '%{name}' has not yet been signed") % { name: certname })
end
end
when 'download_cert'
ssl_context = @machine.ensure_ca_certificates
cert = download_cert(ssl_context)
unless cert
raise Puppet::Error, _("The certificate for '%{name}' has not yet been signed") % { name: certname }
end
when 'generate_request'
generate_request(certname)
when 'verify'
verify(certname)
when 'clean'
possible_extra_args = command_line.args.drop(1)
unless possible_extra_args.empty?
raise Puppet::Error, _(<<~END) % { args: possible_extra_args.join(' ') }
Extra arguments detected: %{args}
Did you mean to run:
puppetserver ca clean --certname <name>
Or:
puppet ssl clean --target <name>
END
end
clean(certname)
when 'bootstrap'
unless Puppet::Util::Log.sendlevel?(:info)
Puppet::Util::Log.level = :info
end
@machine.ensure_client_certificate
Puppet.notice(_("Completed SSL initialization"))
when 'show'
show(certname)
else
raise Puppet::Error, _("Unknown action '%{action}'") % { action: action }
end
end
def show(certname)
password = @cert_provider.load_private_key_password
ssl_context = @ssl_provider.load_context(certname: certname, password: password)
puts ssl_context.client_cert.to_text
end
def submit_request(ssl_context)
key = @cert_provider.load_private_key(Puppet[:certname])
unless key
key = create_key(Puppet[:certname])
@cert_provider.save_private_key(Puppet[:certname], key)
end
csr = @cert_provider.create_request(Puppet[:certname], key)
route = create_route(ssl_context)
route.put_certificate_request(Puppet[:certname], csr, ssl_context: ssl_context)
@cert_provider.save_request(Puppet[:certname], csr)
Puppet.notice _("Submitted certificate request for '%{name}' to %{url}") % { name: Puppet[:certname], url: route.url }
rescue Puppet::HTTP::ResponseError => e
if e.response.code == 400
raise Puppet::Error, _("Could not submit certificate request for '%{name}' to %{url} due to a conflict on the server") % { name: Puppet[:certname], url: route.url }
else
raise Puppet::Error.new(_("Failed to submit certificate request: %{message}") % { message: e.message }, e)
end
rescue => e
raise Puppet::Error.new(_("Failed to submit certificate request: %{message}") % { message: e.message }, e)
end
def generate_request(certname)
key = @cert_provider.load_private_key(certname)
unless key
key = create_key(certname)
@cert_provider.save_private_key(certname, key)
end
csr = @cert_provider.create_request(certname, key)
@cert_provider.save_request(certname, csr)
Puppet.notice _("Generated certificate request in '%{path}'") % { path: @cert_provider.to_path(Puppet[:requestdir], certname) }
rescue => e
raise Puppet::Error.new(_("Failed to generate certificate request: %{message}") % { message: e.message }, e)
end
def download_cert(ssl_context)
key = @cert_provider.load_private_key(Puppet[:certname])
# try to download cert
route = create_route(ssl_context)
Puppet.info _("Downloading certificate '%{name}' from %{url}") % { name: Puppet[:certname], url: route.url }
_, x509 = route.get_certificate(Puppet[:certname], ssl_context: ssl_context)
cert = OpenSSL::X509::Certificate.new(x509)
Puppet.notice _("Downloaded certificate '%{name}' with fingerprint %{fingerprint}") % { name: Puppet[:certname], fingerprint: fingerprint(cert) }
# verify client cert before saving
@ssl_provider.create_context(
cacerts: ssl_context.cacerts, crls: ssl_context.crls, private_key: key, client_cert: cert
)
@cert_provider.save_client_cert(Puppet[:certname], cert)
@cert_provider.delete_request(Puppet[:certname])
cert
rescue Puppet::HTTP::ResponseError => e
if e.response.code == 404
nil
else
raise Puppet::Error.new(_("Failed to download certificate: %{message}") % { message: e.message }, e)
end
rescue => e
raise Puppet::Error.new(_("Failed to download certificate: %{message}") % { message: e.message }, e)
end
def verify(certname)
password = @cert_provider.load_private_key_password
ssl_context = @ssl_provider.load_context(certname: certname, password: password)
# print from root to client
ssl_context.client_chain.reverse.each_with_index do |cert, i|
digest = Puppet::SSL::Digest.new('SHA256', cert.to_der)
if i == ssl_context.client_chain.length - 1
Puppet.notice("Verified client certificate '#{cert.subject.to_utf8}' fingerprint #{digest}")
else
Puppet.notice("Verified CA certificate '#{cert.subject.to_utf8}' fingerprint #{digest}")
end
end
end
def clean(certname)
# make sure cert has been removed from the CA
if certname == Puppet[:ca_server]
cert = nil
begin
ssl_context = @machine.ensure_ca_certificates
route = create_route(ssl_context)
_, cert = route.get_certificate(certname, ssl_context: ssl_context)
rescue Puppet::HTTP::ResponseError => e
if e.response.code.to_i != 404
raise Puppet::Error.new(_("Failed to connect to the CA to determine if certificate %{certname} has been cleaned") % { certname: certname }, e)
end
rescue => e
raise Puppet::Error.new(_("Failed to connect to the CA to determine if certificate %{certname} has been cleaned") % { certname: certname }, e)
end
if cert
raise Puppet::Error, _(<<~END) % { certname: certname }
The certificate %{certname} must be cleaned from the CA first. To fix this,
run the following commands on the CA:
puppetserver ca clean --certname %{certname}
puppet ssl clean
END
end
end
paths = {
'private key' => Puppet[:hostprivkey],
'public key' => Puppet[:hostpubkey],
'certificate request' => Puppet[:hostcsr],
'certificate' => Puppet[:hostcert],
'private key password file' => Puppet[:passfile]
}
if options[:localca]
paths['local CA certificate'] = Puppet[:localcacert]
paths['local CRL'] = Puppet[:hostcrl]
end
paths.each_pair do |label, path|
if Puppet::FileSystem.exist?(path)
Puppet::FileSystem.unlink(path)
Puppet.notice _("Removed %{label} %{path}") % { label: label, path: path }
end
end
end
private
def fingerprint(cert)
Puppet::SSL::Digest.new(nil, cert.to_der)
end
def create_route(ssl_context)
@session.route_to(:ca, ssl_context: ssl_context)
end
def create_key(certname)
if Puppet[:key_type] == 'ec'
Puppet.info _("Creating a new EC SSL key for %{name} using curve %{curve}") % { name: certname, curve: Puppet[:named_curve] }
OpenSSL::PKey::EC.generate(Puppet[:named_curve])
else
Puppet.info _("Creating a new SSL key for %{name}") % { name: certname }
OpenSSL::PKey::RSA.new(Puppet[:keylength].to_i)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/plugin.rb | lib/puppet/application/plugin.rb | # frozen_string_literal: true
require_relative '../../puppet/application/face_base'
class Puppet::Application::Plugin < Puppet::Application::FaceBase
environment_mode :not_required
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/parser.rb | lib/puppet/application/parser.rb | # frozen_string_literal: true
require_relative '../../puppet/application/face_base'
require_relative '../../puppet/face'
class Puppet::Application::Parser < Puppet::Application::FaceBase
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/indirection_base.rb | lib/puppet/application/indirection_base.rb | # frozen_string_literal: true
require_relative '../../puppet/application/face_base'
class Puppet::Application::IndirectionBase < Puppet::Application::FaceBase
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/catalog.rb | lib/puppet/application/catalog.rb | # frozen_string_literal: true
require_relative '../../puppet/application/indirection_base'
class Puppet::Application::Catalog < Puppet::Application::IndirectionBase
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/epp.rb | lib/puppet/application/epp.rb | # frozen_string_literal: true
require_relative '../../puppet/application/face_base'
require_relative '../../puppet/face'
class Puppet::Application::Epp < Puppet::Application::FaceBase
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/help.rb | lib/puppet/application/help.rb | # frozen_string_literal: true
require_relative '../../puppet/application/face_base'
class Puppet::Application::Help < Puppet::Application::FaceBase
environment_mode :not_required
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/facts.rb | lib/puppet/application/facts.rb | # frozen_string_literal: true
require_relative '../../puppet/application/indirection_base'
class Puppet::Application::Facts < Puppet::Application::IndirectionBase
# Allows `puppet facts` actions to be run against environments that
# don't exist locally, such as using the `--environment` flag to make a REST
# request to a specific environment on a master. There is no way to set this
# behavior per-action, so it must be set for the face as a whole.
environment_mode :not_required
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/describe.rb | lib/puppet/application/describe.rb | # frozen_string_literal: true
require_relative '../../puppet/application'
class Formatter
def initialize(width)
@width = width
end
def wrap(txt, opts)
return "" unless txt && !txt.empty?
work = (opts[:scrub] ? scrub(txt) : txt)
indent = opts[:indent] || 0
textLen = @width - indent
patt = Regexp.new("\\A(.{0,#{textLen}})[ \n]")
prefix = " " * indent
res = []
while work.length > textLen
if work =~ patt
res << ::Regexp.last_match(1)
work.slice!(0, ::Regexp.last_match(0).length)
else
res << work.slice!(0, textLen)
end
end
res << work if work.length.nonzero?
prefix + res.join("\n#{prefix}")
end
def header(txt, sep = "-")
"\n#{txt}\n" + sep * txt.size
end
private
def scrub(text)
# For text with no carriage returns, there's nothing to do.
return text if text !~ /\n/
# If we can match an indentation, then just remove that same level of
# indent from every line.
if text =~ /^(\s+)/
indent = ::Regexp.last_match(1)
text.gsub(/^#{indent}/, '')
else
text
end
end
end
class TypeDoc
def initialize
@format = Formatter.new(76)
@types = {}
Puppet::Type.loadall
Puppet::Type.eachtype { |type|
next if type.name == :component
@types[type.name] = type
}
end
def list_types
puts "These are the types known to puppet:\n"
@types.keys.sort_by(&:to_s).each do |name|
type = @types[name]
s = type.doc.gsub(/\s+/, " ")
if s.empty?
s = ".. no documentation .."
else
n = s.index(".") || s.length
if n > 45
s = s[0, 45] + " ..."
else
s = s[0, n]
end
end
printf "%-15s - %s\n", name, s
end
end
def format_type(name, opts)
name = name.to_sym
unless @types.has_key?(name)
puts "Unknown type #{name}"
return
end
type = @types[name]
puts @format.header(name.to_s, "=")
puts @format.wrap(type.doc, :indent => 0, :scrub => true) + "\n\n"
puts @format.header("Parameters")
if opts[:parameters]
format_attrs(type, [:property, :param])
else
list_attrs(type, [:property, :param])
end
if opts[:meta]
puts @format.header("Meta Parameters")
if opts[:parameters]
format_attrs(type, [:meta])
else
list_attrs(type, [:meta])
end
end
if type.providers.size > 0
puts @format.header("Providers")
if opts[:providers]
format_providers(type)
else
list_providers(type)
end
end
end
# List details about attributes
def format_attrs(type, attrs)
docs = {}
type.allattrs.each do |name|
kind = type.attrtype(name)
docs[name] = type.attrclass(name).doc if attrs.include?(kind) && name != :provider
end
docs.sort { |a, b|
a[0].to_s <=> b[0].to_s
}.each { |name, doc|
print "\n- **#{name}**"
if type.key_attributes.include?(name) and name != :name
puts " (*namevar*)"
else
puts ""
end
puts @format.wrap(doc, :indent => 4, :scrub => true)
}
end
# List the names of attributes
def list_attrs(type, attrs)
params = []
type.allattrs.each do |name|
kind = type.attrtype(name)
params << name.to_s if attrs.include?(kind) && name != :provider
end
puts @format.wrap(params.sort.join(", "), :indent => 4)
end
def format_providers(type)
type.providers.sort_by(&:to_s).each { |prov|
puts "\n- **#{prov}**"
puts @format.wrap(type.provider(prov).doc, :indent => 4, :scrub => true)
}
end
def list_providers(type)
list = type.providers.sort_by(&:to_s).join(", ")
puts @format.wrap(list, :indent => 4)
end
end
class Puppet::Application::Describe < Puppet::Application
banner "puppet describe [options] [type]"
option("--short", "-s", "Only list parameters without detail") do |_arg|
options[:parameters] = false
end
option("--providers", "-p")
option("--list", "-l")
option("--meta", "-m")
def summary
_("Display help about resource types available to OpenVox")
end
def help
<<~HELP
puppet-describe(8) -- #{summary}
========
SYNOPSIS
--------
Prints help about Puppet resource types, providers, and metaparameters
installed on an OpenVox node.
USAGE
-----
puppet describe [-h|--help] [-s|--short] [-p|--providers] [-l|--list] [-m|--meta]
OPTIONS
-------
* --help:
Print this help text
* --providers:
Describe providers in detail for each type
* --list:
List all types
* --meta:
List all metaparameters
* --short:
List only parameters without detail
EXAMPLE
-------
$ puppet describe --list
$ puppet describe file --providers
$ puppet describe user -s -m
AUTHOR
------
David Lutterkort
COPYRIGHT
---------
Copyright (c) 2011 Puppet Inc.
Copyright (c) 2024 Vox Pupuli
Licensed under the Apache 2.0 License
HELP
end
def preinit
options[:parameters] = true
end
def main
doc = TypeDoc.new
if options[:list]
doc.list_types
else
options[:types].each { |name| doc.format_type(name, options) }
end
end
def setup
options[:types] = command_line.args.dup
handle_help(nil) unless options[:list] || options[:types].size > 0
$stderr.puts "Warning: ignoring types when listing all types" if options[:list] && options[:types].size > 0
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/filebucket.rb | lib/puppet/application/filebucket.rb | # frozen_string_literal: true
require_relative '../../puppet/application'
class Puppet::Application::Filebucket < Puppet::Application
environment_mode :not_required
option("--bucket BUCKET", "-b")
option("--debug", "-d")
option("--fromdate FROMDATE", "-f")
option("--todate TODATE", "-t")
option("--local", "-l")
option("--remote", "-r")
option("--verbose", "-v")
attr_reader :args
def summary
_("Store and retrieve files in an OpenVox filebucket")
end
def digest_algorithm
Puppet.default_digest_algorithm
end
def help
<<~HELP
puppet-filebucket(8) -- #{summary}
========
SYNOPSIS
--------
A stand-alone OpenVox filebucket client.
USAGE
-----
puppet filebucket <mode> [-h|--help] [-V|--version] [-d|--debug]
[-v|--verbose] [-l|--local] [-r|--remote] [-s|--server <server>]
[-f|--fromdate <date>] [-t|--todate <date>] [-b|--bucket <directory>]
<file> <file> ...
This filebucket client can operate in three modes, with only one mode per call:
backup:
Send one or more files to the specified file bucket. Each sent file is
printed with its resulting #{digest_algorithm} sum.
get:
Return the text associated with an #{digest_algorithm} sum. The text is printed to
stdout, and only one file can be retrieved at a time.
restore:
Given a file path and an #{digest_algorithm} sum, store the content associated with
the sum into the specified file path. You can specify an entirely new
path to this argument; you are not restricted to restoring the content
to its original location.
diff:
Print a diff in unified format between two checksums in the filebucket
or between a checksum and its matching file.
list:
List all files in the current local filebucket. Listing remote
filebuckets is not allowed.
DESCRIPTION
-----------
This is a stand-alone filebucket client for sending files to a local or
central filebucket.
Note that 'filebucket' defaults to using a network-based filebucket
available on the server named 'puppet'. To use this, you'll have to be
running as a user with valid Puppet certificates. Alternatively, you can
use your local file bucket by specifying '--local', or by specifying
'--bucket' with a local path.
**Important**: When you enable and use the backup option, and by extension
the filebucket resource, you must ensure that sufficient disk space is
available for the file backups. Generally, you can provide the disk space
by using one of the following two options:
- Use a `find` command and `crontab` entry to retain only the last X days
of file backups. For example:
```shell
find /opt/puppetlabs/server/data/puppetserver/bucket -type f -mtime +45 -atime +45 -print0 | xargs -0 rm
```
- Restrict the directory to a maximum size after which the oldest items are removed.
OPTIONS
-------
Note that any setting that's valid in the configuration
file is also a valid long argument. For example, 'ssldir' is a valid
setting, so you can specify '--ssldir <directory>' as an
argument.
See the configuration file documentation at
https://puppet.com/docs/puppet/latest/configuration.html for the
full list of acceptable parameters. A commented list of all
configuration options can also be generated by running puppet with
'--genconfig'.
* --bucket:
Specify a local filebucket path. This overrides the default path
set in '$clientbucketdir'.
* --debug:
Enable full debugging.
* --fromdate:
(list only) Select bucket files from 'fromdate'.
* --help:
Print this help message.
* --local:
Use the local filebucket. This uses the default configuration
information and the bucket located at the '$clientbucketdir'
setting by default. If '--bucket' is set, that path is used instead.
* --remote:
Use a remote filebucket. This uses the default configuration
information and the bucket located at the '$bucketdir' setting
by default.
* --server_list:
A list of comma separated servers; only the first entry is used for file storage.
This setting takes precidence over `server`.
* --server:
The server to use for file storage. This setting is only used if `server_list`
is not set.
* --todate:
(list only) Select bucket files until 'todate'.
* --verbose:
Print extra information.
* --version:
Print version information.
EXAMPLES
--------
## Backup a file to the filebucket, then restore it to a temporary directory
$ puppet filebucket backup /etc/passwd
/etc/passwd: 429b225650b912a2ee067b0a4cf1e949
$ puppet filebucket restore /tmp/passwd 429b225650b912a2ee067b0a4cf1e949
## Diff between two files in the filebucket
$ puppet filebucket -l diff d43a6ecaa892a1962398ac9170ea9bf2 7ae322f5791217e031dc60188f4521ef
1a2
> again
## Diff between the file in the filebucket and a local file
$ puppet filebucket -l diff d43a6ecaa892a1962398ac9170ea9bf2 /tmp/testFile
1a2
> again
## Backup a file to the filebucket and observe that it keeps each backup separate
$ puppet filebucket -l list
d43a6ecaa892a1962398ac9170ea9bf2 2015-05-11 09:27:56 /tmp/TestFile
$ echo again >> /tmp/TestFile
$ puppet filebucket -l backup /tmp/TestFile
/tmp/TestFile: 7ae322f5791217e031dc60188f4521ef
$ puppet filebucket -l list
d43a6ecaa892a1962398ac9170ea9bf2 2015-05-11 09:27:56 /tmp/TestFile
7ae322f5791217e031dc60188f4521ef 2015-05-11 09:52:15 /tmp/TestFile
## List files in a filebucket within date ranges
$ puppet filebucket -l -f 2015-01-01 -t 2015-01-11 list
<Empty Output>
$ puppet filebucket -l -f 2015-05-10 list
d43a6ecaa892a1962398ac9170ea9bf2 2015-05-11 09:27:56 /tmp/TestFile
7ae322f5791217e031dc60188f4521ef 2015-05-11 09:52:15 /tmp/TestFile
$ puppet filebucket -l -f "2015-05-11 09:30:00" list
7ae322f5791217e031dc60188f4521ef 2015-05-11 09:52:15 /tmp/TestFile
$ puppet filebucket -l -t "2015-05-11 09:30:00" list
d43a6ecaa892a1962398ac9170ea9bf2 2015-05-11 09:27:56 /tmp/TestFile
## Manage files in a specific local filebucket
$ puppet filebucket -b /tmp/TestBucket backup /tmp/TestFile2
/tmp/TestFile2: d41d8cd98f00b204e9800998ecf8427e
$ puppet filebucket -b /tmp/TestBucket list
d41d8cd98f00b204e9800998ecf8427e 2015-05-11 09:33:22 /tmp/TestFile2
## From a Puppet Server, list files in the server bucketdir
$ puppet filebucket -b $(puppet config print bucketdir --section server) list
d43a6ecaa892a1962398ac9170ea9bf2 2015-05-11 09:27:56 /tmp/TestFile
7ae322f5791217e031dc60188f4521ef 2015-05-11 09:52:15 /tmp/TestFile
AUTHOR
------
Luke Kanies
COPYRIGHT
---------
Copyright (c) 2011 Puppet Inc.
Copyright (c) 2024 Vox Pupuli
Licensed under the Apache 2.0 License
HELP
end
def run_command
@args = command_line.args
command = args.shift
return send(command) if %w[get backup restore diff list].include? command
help
end
def get
digest = args.shift
out = @client.getfile(digest)
print out
end
def backup
raise _("You must specify a file to back up") unless args.length > 0
args.each do |file|
unless Puppet::FileSystem.exist?(file)
$stderr.puts _("%{file}: no such file") % { file: file }
next
end
unless FileTest.readable?(file)
$stderr.puts _("%{file}: cannot read file") % { file: file }
next
end
digest = @client.backup(file)
puts "#{file}: #{digest}"
end
end
def list
fromdate = options[:fromdate]
todate = options[:todate]
out = @client.list(fromdate, todate)
print out
end
def restore
file = args.shift
digest = args.shift
@client.restore(file, digest)
end
def diff
raise Puppet::Error, _("Need exactly two arguments: filebucket diff <file_a> <file_b>") unless args.count == 2
left = args.shift
right = args.shift
if Puppet::FileSystem.exist?(left)
# It's a file
file_a = left
checksum_a = nil
else
file_a = nil
checksum_a = left
end
if Puppet::FileSystem.exist?(right)
# It's a file
file_b = right
checksum_b = nil
else
file_b = nil
checksum_b = right
end
if (checksum_a || file_a) && (checksum_b || file_b)
Puppet.info(_("Comparing %{checksum_a} %{checksum_b} %{file_a} %{file_b}") % { checksum_a: checksum_a, checksum_b: checksum_b, file_a: file_a, file_b: file_b })
print @client.diff(checksum_a, checksum_b, file_a, file_b)
else
raise Puppet::Error, _("Need exactly two arguments: filebucket diff <file_a> <file_b>")
end
end
def setup
Puppet::Log.newdestination(:console)
@client = nil
@server = nil
Signal.trap(:INT) do
$stderr.puts _("Cancelling")
exit(1)
end
if options[:debug]
Puppet::Log.level = :debug
elsif options[:verbose]
Puppet::Log.level = :info
end
exit(Puppet.settings.print_configs ? 0 : 1) if Puppet.settings.print_configs?
require_relative '../../puppet/file_bucket/dipper'
begin
if options[:local] or options[:bucket]
path = options[:bucket] || Puppet[:clientbucketdir]
@client = Puppet::FileBucket::Dipper.new(:Path => path)
else
session = Puppet.lookup(:http_session)
api = session.route_to(:puppet)
@client = Puppet::FileBucket::Dipper.new(Server: api.url.host, Port: api.url.port)
end
rescue => detail
Puppet.log_exception(detail)
exit(1)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/apply.rb | lib/puppet/application/apply.rb | # frozen_string_literal: true
require_relative '../../puppet/application'
require_relative '../../puppet/configurer'
require_relative '../../puppet/util/profiler/aggregate'
class Puppet::Application::Apply < Puppet::Application
require_relative '../../puppet/util/splayer'
include Puppet::Util::Splayer
option("--debug", "-d")
option("--execute EXECUTE", "-e") do |arg|
options[:code] = arg
end
option("--loadclasses", "-L")
option("--test", "-t")
option("--verbose", "-v")
option("--use-nodes")
option("--detailed-exitcodes")
option("--write-catalog-summary") do |arg|
Puppet[:write_catalog_summary] = arg
end
option("--catalog catalog", "-c catalog") do |arg|
options[:catalog] = arg
end
option("--logdest LOGDEST", "-l") do |arg|
handle_logdest_arg(arg)
end
option("--parseonly") do |_args|
puts "--parseonly has been removed. Please use 'puppet parser validate <manifest>'"
exit 1
end
def summary
_("Apply Puppet manifests locally via OpenVox")
end
def help
<<~HELP
puppet-apply(8) -- #{summary}
========
SYNOPSIS
--------
Applies a standalone Puppet manifest to the local system.
USAGE
-----
puppet apply [-h|--help] [-V|--version] [-d|--debug] [-v|--verbose]
[-e|--execute] [--detailed-exitcodes] [-L|--loadclasses]
[-l|--logdest syslog|eventlog|<ABS FILEPATH>|console] [--noop]
[--catalog <catalog>] [--write-catalog-summary] <file>
DESCRIPTION
-----------
This is the standalone puppet execution tool; use it to apply
individual manifests.
When provided with a modulepath, via command line or config file, puppet
apply can effectively mimic the catalog that would be served by OpenVox
server with access to the same modules, although there are some subtle
differences. When combined with scheduling and an automated system for
pushing manifests, this can be used to implement a serverless site.
Most users should use 'puppet agent' and 'puppet master' for site-wide
manifests.
OPTIONS
-------
Any setting that's valid in the configuration
file is a valid long argument for puppet apply. For example, 'tags' is a
valid setting, so you can specify '--tags <class>,<tag>'
as an argument.
See the configuration file documentation at
https://puppet.com/docs/puppet/latest/configuration.html for the
full list of acceptable parameters. You can generate a commented list of all
configuration options by running puppet with
'--genconfig'.
* --debug:
Enable full debugging.
* --detailed-exitcodes:
Provide extra information about the run via exit codes. If enabled, 'puppet
apply' will use the following exit codes:
0: The run succeeded with no changes or failures; the system was already in
the desired state.
1: The run failed.
2: The run succeeded, and some resources were changed.
4: The run succeeded, and some resources failed.
6: The run succeeded, and included both changes and failures.
* --help:
Print this help message
* --loadclasses:
Load any stored classes. 'puppet agent' caches configured classes
(usually at /etc/puppetlabs/puppet/classes.txt), and setting this option causes
all of those classes to be set in your puppet manifest.
* --logdest:
Where to send log messages. Choose between 'syslog' (the POSIX syslog
service), 'eventlog' (the Windows Event Log), 'console', or the path to a log
file. Defaults to 'console'.
Multiple destinations can be set using a comma separated list
(eg: `/path/file1,console,/path/file2`)"
A path ending with '.json' will receive structured output in JSON format. The
log file will not have an ending ']' automatically written to it due to the
appending nature of logging. It must be appended manually to make the content
valid JSON.
A path ending with '.jsonl' will receive structured output in JSON Lines
format.
* --noop:
Use 'noop' mode where Puppet runs in a no-op or dry-run mode. This
is useful for seeing what changes Puppet will make without actually
executing the changes.
* --execute:
Execute a specific piece of Puppet code
* --test:
Enable the most common options used for testing. These are 'verbose',
'detailed-exitcodes' and 'show_diff'.
* --verbose:
Print extra information.
* --catalog:
Apply a JSON catalog (such as one generated with 'puppet master --compile'). You can
either specify a JSON file or pipe in JSON from standard input.
* --write-catalog-summary
After compiling the catalog saves the resource list and classes list to the node
in the state directory named classes.txt and resources.txt
EXAMPLE
-------
$ puppet apply -e 'notify { "hello world": }'
$ puppet apply -l /tmp/manifest.log manifest.pp
$ puppet apply --modulepath=/root/dev/modules -e "include ntpd::server"
$ puppet apply --catalog catalog.json
AUTHOR
------
Luke Kanies
COPYRIGHT
---------
Copyright (c) 2011 Puppet Inc.
Copyright (c) 2024 Vox Pupuli
Licensed under the Apache 2.0 License
HELP
end
def app_defaults
super.merge({
:default_file_terminus => :file_server,
:write_catalog_summary => false
})
end
def run_command
if options[:catalog]
apply
else
main
end
ensure
if @profiler
Puppet::Util::Profiler.remove_profiler(@profiler)
@profiler.shutdown
end
end
def apply
if options[:catalog] == "-"
text = $stdin.read
else
text = Puppet::FileSystem.read(options[:catalog], :encoding => 'utf-8')
end
env = Puppet.lookup(:environments).get(Puppet[:environment])
Puppet.override(:current_environment => env, :loaders => create_loaders(env)) do
catalog = read_catalog(text)
apply_catalog(catalog)
end
end
def main
# rubocop:disable Layout/ExtraSpacing
manifest = get_manifest() # Get either a manifest or nil if apply should use content of Puppet[:code]
splay # splay if needed
facts = get_facts() # facts or nil
node = get_node() # node or error
apply_environment = get_configured_environment(node, manifest)
# rubocop:enable Layout/ExtraSpacing
# TRANSLATORS "puppet apply" is a program command and should not be translated
Puppet.override({ :current_environment => apply_environment, :loaders => create_loaders(apply_environment) }, _("For puppet apply")) do
configure_node_facts(node, facts)
# Allow users to load the classes that puppet agent creates.
if options[:loadclasses]
file = Puppet[:classfile]
if Puppet::FileSystem.exist?(file)
unless FileTest.readable?(file)
$stderr.puts _("%{file} is not readable") % { file: file }
exit(63)
end
node.classes = Puppet::FileSystem.read(file, :encoding => 'utf-8').split(/\s+/)
end
end
begin
# Compile the catalog
starttime = Time.now
# When compiling, the compiler traps and logs certain errors
# Those that do not lead to an immediate exit are caught by the general
# rule and gets logged.
#
catalog =
begin
Puppet::Resource::Catalog.indirection.find(node.name, :use_node => node)
rescue Puppet::Error
# already logged and handled by the compiler, including Puppet::ParseErrorWithIssue
exit(1)
end
# Resolve all deferred values and replace them / mutate the catalog
Puppet::Pops::Evaluator::DeferredResolver.resolve_and_replace(node.facts, catalog, apply_environment, Puppet[:preprocess_deferred])
# Translate it to a RAL catalog
catalog = catalog.to_ral
catalog.finalize
catalog.retrieval_duration = Time.now - starttime
# We accept either the global option `--write_catalog_summary`
# corresponding to the new setting, or the application option
# `--write-catalog-summary`. The latter is needed to maintain backwards
# compatibility.
#
# Puppet settings parse global options using PuppetOptionParser, but it
# only recognizes underscores, not dashes.
# The base application parses app specific options using ruby's builtin
# OptionParser. As of ruby 2.4, it will accept either underscores or
# dashes, but prefer dashes.
#
# So if underscores are used, the PuppetOptionParser will parse it and
# store that in Puppet[:write_catalog_summary]. If dashes are used,
# OptionParser will parse it, and set Puppet[:write_catalog_summary]. In
# either case, settings will contain the correct value.
if Puppet[:write_catalog_summary]
catalog.write_class_file
catalog.write_resource_file
end
exit_status = apply_catalog(catalog)
if !exit_status
exit(1)
elsif options[:detailed_exitcodes] then
exit(exit_status)
else
exit(0)
end
rescue => detail
Puppet.log_exception(detail)
exit(1)
end
end
end
# Enable all of the most common test options.
def setup_test
Puppet.settings.handlearg("--no-splay")
Puppet.settings.handlearg("--show_diff")
options[:verbose] = true
options[:detailed_exitcodes] = true
end
def setup
setup_test if options[:test]
exit(Puppet.settings.print_configs ? 0 : 1) if Puppet.settings.print_configs?
handle_logdest_arg(Puppet[:logdest])
Puppet::Util::Log.newdestination(:console) unless options[:setdest]
Signal.trap(:INT) do
$stderr.puts _("Exiting")
exit(1)
end
Puppet.settings.use :main, :agent, :ssl
if Puppet[:catalog_cache_terminus]
Puppet::Resource::Catalog.indirection.cache_class = Puppet[:catalog_cache_terminus]
end
# we want the last report to be persisted locally
Puppet::Transaction::Report.indirection.cache_class = :yaml
set_log_level
if Puppet[:profile]
@profiler = Puppet::Util::Profiler.add_profiler(Puppet::Util::Profiler::Aggregate.new(Puppet.method(:info), "apply"))
end
end
private
def create_loaders(env)
# Ignore both 'cached_puppet_lib' and pcore resource type loaders
Puppet::Pops::Loaders.new(env, false, false)
end
def read_catalog(text)
facts = get_facts()
node = get_node()
configured_environment = get_configured_environment(node)
# TRANSLATORS "puppet apply" is a program command and should not be translated
Puppet.override({ :current_environment => configured_environment }, _("For puppet apply")) do
configure_node_facts(node, facts)
# NOTE: Does not set rich_data = true automatically (which would ensure always reading catalog with rich data
# on (seemingly the right thing to do)), but that would remove the ability to test what happens when a
# rich catalog is processed without rich_data being turned on.
format = Puppet::Resource::Catalog.default_format
begin
catalog = Puppet::Resource::Catalog.convert_from(format, text)
rescue => detail
raise Puppet::Error, _("Could not deserialize catalog from %{format}: %{detail}") % { format: format, detail: detail }, detail.backtrace
end
# Resolve all deferred values and replace them / mutate the catalog
Puppet::Pops::Evaluator::DeferredResolver.resolve_and_replace(node.facts, catalog, configured_environment, Puppet[:preprocess_deferred])
catalog.to_ral
end
end
def apply_catalog(catalog)
configurer = Puppet::Configurer.new
configurer.run(:catalog => catalog, :pluginsync => false)
end
# Returns facts or nil
#
def get_facts
facts = nil
unless Puppet[:node_name_fact].empty?
# Collect our facts.
facts = Puppet::Node::Facts.indirection.find(Puppet[:node_name_value])
raise _("Could not find facts for %{node}") % { node: Puppet[:node_name_value] } unless facts
Puppet[:node_name_value] = facts.values[Puppet[:node_name_fact]]
facts.name = Puppet[:node_name_value]
end
facts
end
# Returns the node or raises and error if node not found.
#
def get_node
node = Puppet::Node.indirection.find(Puppet[:node_name_value])
raise _("Could not find node %{node}") % { node: Puppet[:node_name_value] } unless node
node
end
# Returns either a manifest (filename) or nil if apply should use content of Puppet[:code]
#
def get_manifest
manifest = nil
# Set our code or file to use.
if options[:code] or command_line.args.length == 0
Puppet[:code] = options[:code] || STDIN.read
else
manifest = command_line.args.shift
raise _("Could not find file %{manifest}") % { manifest: manifest } unless Puppet::FileSystem.exist?(manifest)
Puppet.warning(_("Only one file can be applied per run. Skipping %{files}") % { files: command_line.args.join(', ') }) if command_line.args.size > 0
end
manifest
end
# Returns a configured environment, if a manifest is given it overrides what is configured for the environment
# specified by the node (or the current_environment found in the Puppet context).
# The node's resolved environment is modified if needed.
#
def get_configured_environment(node, manifest = nil)
configured_environment = node.environment || Puppet.lookup(:current_environment)
apply_environment = manifest ?
configured_environment.override_with(:manifest => manifest) :
configured_environment
# Modify the node descriptor to use the special apply_environment.
# It is based on the actual environment from the node, or the locally
# configured environment if the node does not specify one.
# If a manifest file is passed on the command line, it overrides
# the :manifest setting of the apply_environment.
node.environment = apply_environment
apply_environment
end
# Mixes the facts into the node, and mixes in server facts
def configure_node_facts(node, facts)
node.merge(facts.values) if facts
# Add server facts so $server_facts[environment] exists when doing a puppet apply
node.add_server_facts({})
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/config.rb | lib/puppet/application/config.rb | # frozen_string_literal: true
require_relative '../../puppet/application/face_base'
class Puppet::Application::Config < Puppet::Application::FaceBase
environment_mode :not_required
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/face_base.rb | lib/puppet/application/face_base.rb | # frozen_string_literal: true
require_relative '../../puppet/application'
require_relative '../../puppet/face'
require 'optparse'
class Puppet::Application::FaceBase < Puppet::Application
option("--debug", "-d") do |_arg|
set_log_level(:debug => true)
end
option("--verbose", "-v") do |_|
set_log_level(:verbose => true)
end
option("--render-as FORMAT") do |format|
self.render_as = format.to_sym
end
option("--help", "-h") do |_arg|
if action && !@is_default_action
# Only invoke help on the action if it was specified, not if
# it was the default action.
puts Puppet::Face[:help, :current].help(face.name, action.name)
else
puts Puppet::Face[:help, :current].help(face.name)
end
exit(0)
end
attr_reader :render_as
attr_accessor :face, :action, :type, :arguments
def render_as=(format)
@render_as = Puppet::Network::FormatHandler.format(format)
@render_as or raise ArgumentError, _("I don't know how to render '%{format}'") % { format: format }
end
def render(result, args_and_options)
hook = action.when_rendering(render_as.name)
if hook
# when defining when_rendering on your action you can optionally
# include arguments and options
if hook.arity > 1
result = hook.call(result, *args_and_options)
else
result = hook.call(result)
end
end
render_as.render(result)
end
def preinit
super
Signal.trap(:INT) do
$stderr.puts _("Cancelling Face")
exit(0)
end
end
def parse_options
# We need to parse enough of the command line out early, to identify what
# the action is, so that we can obtain the full set of options to parse.
# REVISIT: These should be configurable versions, through a global
# '--version' option, but we don't implement that yet... --daniel 2011-03-29
@type = Puppet::Util::ConstantInflector.constant2file(self.class.name.to_s.sub(/.+:/, '')).to_sym
@face = Puppet::Face[@type, :current]
# Now, walk the command line and identify the action. We skip over
# arguments based on introspecting the action and all, and find the first
# non-option word to use as the action.
action_name = nil
index = -1
until action_name or (index += 1) >= command_line.args.length
item = command_line.args[index]
if item =~ /^-/
option = @face.options.find do |name|
item =~ /^-+#{name.to_s.gsub(/[-_]/, '[-_]')}(?:[ =].*)?$/
end
if option
option = @face.get_option(option)
# If we have an inline argument, just carry on. We don't need to
# care about optional vs mandatory in that case because we do a real
# parse later, and that will totally take care of raising the error
# when we get there. --daniel 2011-04-04
if option.takes_argument? and !item.index('=')
index += 1 unless
option.optional_argument? and command_line.args[index + 1] =~ /^-/
end
else
option = find_global_settings_argument(item)
if option
unless Puppet.settings.boolean? option.name
# As far as I can tell, we treat non-bool options as always having
# a mandatory argument. --daniel 2011-04-05
# ... But, the mandatory argument will not be the next item if an = is
# employed in the long form of the option. --jeffmccune 2012-09-18
index += 1 unless item =~ /^--#{option.name}=/
end
else
option = find_application_argument(item)
if option
index += 1 if option[:argument] and !(option[:optional])
else
raise OptionParser::InvalidOption, item.sub(/=.*$/, '')
end
end
end
else
# Stash away the requested action name for later, and try to fetch the
# action object it represents; if this is an invalid action name that
# will be nil, and handled later.
action_name = item.to_sym
@action = Puppet::Face.find_action(@face.name, action_name)
@face = @action.face if @action
end
end
if @action.nil?
@action = @face.get_default_action()
if @action
@is_default_action = true
else
# First try to handle global command line options
# But ignoring invalid options as this is a invalid action, and
# we want the error message for that instead.
begin
super
rescue OptionParser::InvalidOption
end
face = @face.name
action = action_name.nil? ? 'default' : "'#{action_name}'"
msg = _("'%{face}' has no %{action} action. See `puppet help %{face}`.") % { face: face, action: action }
Puppet.err(msg)
Puppet::Util::Log.force_flushqueue()
exit false
end
end
# Now we can interact with the default option code to build behaviour
# around the full set of options we now know we support.
@action.options.each do |o|
o = @action.get_option(o) # make it the object.
self.class.option(*o.optparse) # ...and make the CLI parse it.
end
# ...and invoke our parent to parse all the command line options.
super
end
def find_global_settings_argument(item)
Puppet.settings.each do |_name, object|
object.optparse_args.each do |arg|
next unless arg =~ /^-/
# sadly, we have to emulate some of optparse here...
pattern = /^#{arg.sub('[no-]', '').sub(/[ =].*$/, '')}(?:[ =].*)?$/
pattern.match item and return object
end
end
nil # nothing found.
end
def find_application_argument(item)
self.class.option_parser_commands.each do |options, _function|
options.each do |option|
next unless option =~ /^-/
pattern = /^#{option.sub('[no-]', '').sub(/[ =].*$/, '')}(?:[ =].*)?$/
next unless pattern.match(item)
return {
:argument => option =~ /[ =]/,
:optional => option =~ /[ =]\[/
}
end
end
nil # not found
end
def setup
Puppet::Util::Log.newdestination :console
@arguments = command_line.args
# Note: because of our definition of where the action is set, we end up
# with it *always* being the first word of the remaining set of command
# line arguments. So, strip that off when we construct the arguments to
# pass down to the face action. --daniel 2011-04-04
# Of course, now that we have default actions, we should leave the
# "action" name on if we didn't actually consume it when we found our
# action.
@arguments.delete_at(0) unless @is_default_action
# We copy all of the app options to the end of the call; This allows each
# action to read in the options. This replaces the older model where we
# would invoke the action with options set as global state in the
# interface object. --daniel 2011-03-28
@arguments << options
# If we don't have a rendering format, set one early.
self.render_as ||= @action.render_as || :console
end
def main
status = false
# Call the method associated with the provided action (e.g., 'find').
unless @action
puts Puppet::Face[:help, :current].help(@face.name)
raise _("%{face} does not respond to action %{arg}") % { face: face, arg: arguments.first }
end
# We need to do arity checking here because this is generic code
# calling generic methods – that have argument defaulting. We need to
# make sure we don't accidentally pass the options as the first
# argument to a method that takes one argument. eg:
#
# puppet facts find
# => options => {}
# @arguments => [{}]
# => @face.send :bar, {}
#
# def face.bar(argument, options = {})
# => bar({}, {}) # oops! we thought the options were the
# # positional argument!!
#
# We could also fix this by making it mandatory to pass the options on
# every call, but that would make the Ruby API much more annoying to
# work with; having the defaulting is a much nicer convention to have.
#
# We could also pass the arguments implicitly, by having a magic
# 'options' method that was visible in the scope of the action, which
# returned the right stuff.
#
# That sounds attractive, but adds complications to all sorts of
# things, especially when you think about how to pass options when you
# are writing Ruby code that calls multiple faces. Especially if
# faces are involved in that. ;)
#
# --daniel 2011-04-27
if (arity = @action.positional_arg_count) > 0
unless (count = arguments.length) == arity then
raise ArgumentError, n_("puppet %{face} %{action} takes %{arg_count} argument, but you gave %{given_count}", "puppet %{face} %{action} takes %{arg_count} arguments, but you gave %{given_count}", arity - 1) % { face: @face.name, action: @action.name, arg_count: arity - 1, given_count: count - 1 }
end
end
if @face.deprecated?
Puppet.deprecation_warning(_("'puppet %{face}' is deprecated and will be removed in a future release") % { face: @face.name })
end
result = @face.send(@action.name, *arguments)
puts render(result, arguments) unless result.nil?
status = true
# We need an easy way for the action to set a specific exit code, so we
# rescue SystemExit here; This allows each action to set the desired exit
# code by simply calling Kernel::exit. eg:
#
# exit(2)
#
# --kelsey 2012-02-14
rescue SystemExit => detail
status = detail.status
rescue => detail
Puppet.log_exception(detail)
Puppet.err _("Try 'puppet help %{face} %{action}' for usage") % { face: @face.name, action: @action.name }
ensure
exit status
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/module.rb | lib/puppet/application/module.rb | # frozen_string_literal: true
require_relative '../../puppet/application/face_base'
class Puppet::Application::Module < Puppet::Application::FaceBase
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/lookup.rb | lib/puppet/application/lookup.rb | # frozen_string_literal: true
require_relative '../../puppet/application'
require_relative '../../puppet/pops'
require_relative '../../puppet/node'
require_relative '../../puppet/node/server_facts'
require_relative '../../puppet/parser/compiler'
class Puppet::Application::Lookup < Puppet::Application
RUN_HELP = _("Run 'puppet lookup --help' for more details").freeze
DEEP_MERGE_OPTIONS = '--knock-out-prefix, --sort-merged-arrays, and --merge-hash-arrays'
TRUSTED_INFORMATION_FACTS = %w[hostname domain fqdn clientcert].freeze
run_mode :server
# Options for lookup
option('--merge TYPE') do |arg|
options[:merge] = arg
end
option('--debug', '-d')
option('--verbose', '-v')
option('--render-as FORMAT') do |format|
options[:render_as] = format.downcase.to_sym
end
option('--type TYPE_STRING') do |arg|
options[:type] = arg
end
option('--compile', '-c')
option('--knock-out-prefix PREFIX_STRING') do |arg|
options[:prefix] = arg
end
option('--sort-merged-arrays')
option('--merge-hash-arrays')
option('--explain')
option('--explain-options')
option('--default VALUE') do |arg|
options[:default_value] = arg
end
# not yet supported
option('--trusted')
# Options for facts/scope
option('--node NODE_NAME') do |arg|
options[:node] = arg
end
option('--facts FACT_FILE') do |arg|
options[:fact_file] = arg
end
def app_defaults
super.merge({
:facts_terminus => 'yaml'
})
end
def setup_logs
# This sets up logging based on --debug or --verbose if they are set in `options`
set_log_level
# This uses console for everything that is not a compilation
Puppet::Util::Log.newdestination(:console)
end
def setup_terminuses
require_relative '../../puppet/file_serving/content'
require_relative '../../puppet/file_serving/metadata'
Puppet::FileServing::Content.indirection.terminus_class = :file_server
Puppet::FileServing::Metadata.indirection.terminus_class = :file_server
Puppet::FileBucket::File.indirection.terminus_class = :file
end
def setup
setup_logs
exit(Puppet.settings.print_configs ? 0 : 1) if Puppet.settings.print_configs?
if options[:node]
Puppet::Util.skip_external_facts do
Puppet.settings.use :main, :server, :ssl, :metrics
end
else
Puppet.settings.use :main, :server, :ssl, :metrics
end
setup_terminuses
end
def summary
_("Interactive Hiera lookup for OpenVox")
end
def help
<<~HELP
puppet-lookup(8) -- #{summary}
========
SYNOPSIS
--------
Does Hiera lookups from the command line.
Since this command needs access to your Hiera data, make sure to run it on a
node that has a copy of that data. This usually means logging into an OpenVox
server node and running 'puppet lookup' with sudo.
The most common version of this command is:
'puppet lookup <KEY> --node <NAME> --environment <ENV> --explain'
USAGE
-----
puppet lookup [--help] [--type <TYPESTRING>] [--merge first|unique|hash|deep]
[--knock-out-prefix <PREFIX-STRING>] [--sort-merged-arrays]
[--merge-hash-arrays] [--explain] [--environment <ENV>]
[--default <VALUE>] [--node <NODE-NAME>] [--facts <FILE>]
[--compile]
[--render-as s|json|yaml|binary|msgpack] <keys>
DESCRIPTION
-----------
The lookup command is a CLI for Puppet's 'lookup()' function. It searches your
Hiera data and returns a value for the requested lookup key, so you can test and
explore your data. It is a modern replacement for the 'hiera' command.
Lookup uses the setting for global hiera.yaml from puppet's config,
and the environment to find the environment level hiera.yaml as well as the
resulting modulepath for the environment (for hiera.yaml files in modules).
Hiera usually relies on a node's facts to locate the relevant data sources. By
default, 'puppet lookup' uses facts from the node you run the command on, but
you can get data for any other node with the '--node <NAME>' option. If
possible, the lookup command will use the requested node's real stored facts
from PuppetDB; if PuppetDB isn't configured or you want to provide arbitrary
fact values, you can pass alternate facts as a JSON or YAML file with '--facts
<FILE>'.
If you're debugging your Hiera data and want to see where values are coming
from, use the '--explain' option.
If '--explain' isn't specified, lookup exits with 0 if a value was found and 1
otherwise. With '--explain', lookup always exits with 0 unless there is a major
error.
You can provide multiple lookup keys to this command, but it only returns a
value for the first found key, omitting the rest.
For more details about how Hiera works, see the Hiera documentation:
https://puppet.com/docs/puppet/latest/hiera_intro.html
OPTIONS
-------
* --help:
Print this help message.
* --explain
Explain the details of how the lookup was performed and where the final value
came from (or the reason no value was found).
* --node <NODE-NAME>
Specify which node to look up data for; defaults to the node where the command
is run. Since Hiera's purpose is to provide different values for different
nodes (usually based on their facts), you'll usually want to use some specific
node's facts to explore your data. If the node where you're running this
command is configured to talk to PuppetDB, the command will use the requested
node's most recent facts. Otherwise, you can override facts with the '--facts'
option.
* --facts <FILE>
Specify a .json or .yaml file of key => value mappings to override the facts
for this lookup. Any facts not specified in this file maintain their
original value.
* --environment <ENV>
Like with most Puppet commands, you can specify an environment on the command
line. This is important for lookup because different environments can have
different Hiera data. This environment will be always be the one used regardless
of any other factors.
* --merge first|unique|hash|deep:
Specify the merge behavior, overriding any merge behavior from the data's
lookup_options. 'first' returns the first value found. 'unique' appends
everything to a merged, deduplicated array. 'hash' performs a simple hash
merge by overwriting keys of lower lookup priority. 'deep' performs a deep
merge on values of Array and Hash type. There are additional options that can
be used with 'deep'.
* --knock-out-prefix <PREFIX-STRING>
Can be used with the 'deep' merge strategy. Specifies a prefix to indicate a
value should be removed from the final result.
* --sort-merged-arrays
Can be used with the 'deep' merge strategy. When this flag is used, all
merged arrays are sorted.
* --merge-hash-arrays
Can be used with the 'deep' merge strategy. When this flag is used, hashes
WITHIN arrays are deep-merged with their counterparts by position.
* --explain-options
Explain whether a lookup_options hash affects this lookup, and how that hash
was assembled. (lookup_options is how Hiera configures merge behavior in data.)
* --default <VALUE>
A value to return if Hiera can't find a value in data. For emulating calls to
the 'lookup()' function that include a default.
* --type <TYPESTRING>:
Assert that the value has the specified type. For emulating calls to the
'lookup()' function that include a data type.
* --compile
Perform a full catalog compilation prior to the lookup. If your hierarchy and
data only use the $facts, $trusted, and $server_facts variables, you don't
need this option; however, if your Hiera configuration uses arbitrary
variables set by a Puppet manifest, you might need this option to get accurate
data. No catalog compilation takes place unless this flag is given.
* --render-as s|json|yaml|binary|msgpack
Specify the output format of the results; "s" means plain text. The default
when producing a value is yaml and the default when producing an explanation
is s.
EXAMPLE
-------
To look up 'key_name' using the Puppet Server node's facts:
$ puppet lookup key_name
To look up 'key_name' using the Puppet Server node's arbitrary variables from a manifest, and
classify the node if applicable:
$ puppet lookup key_name --compile
To look up 'key_name' using the Puppet Server node's facts, overridden by facts given in a file:
$ puppet lookup key_name --facts fact_file.yaml
To look up 'key_name' with agent.local's facts:
$ puppet lookup --node agent.local key_name
To get the first value found for 'key_name_one' and 'key_name_two'
with agent.local's facts while merging values and knocking out
the prefix 'foo' while merging:
$ puppet lookup --node agent.local --merge deep --knock-out-prefix foo key_name_one key_name_two
To lookup 'key_name' with agent.local's facts, and return a default value of
'bar' if nothing was found:
$ puppet lookup --node agent.local --default bar key_name
To see an explanation of how the value for 'key_name' would be found, using
agent.local's facts:
$ puppet lookup --node agent.local --explain key_name
COPYRIGHT
---------
Copyright (c) 2015 Puppet Inc.
Copyright (c) 2024 Vox Pupuli
Licensed under the Apache 2.0 License
HELP
end
def main
keys = command_line.args
if (options[:sort_merged_arrays] || options[:merge_hash_arrays] || options[:prefix]) && options[:merge] != 'deep'
raise _("The options %{deep_merge_opts} are only available with '--merge deep'\n%{run_help}") % { deep_merge_opts: DEEP_MERGE_OPTIONS, run_help: RUN_HELP }
end
use_default_value = !options[:default_value].nil?
merge_options = nil
merge = options[:merge]
unless merge.nil?
strategies = Puppet::Pops::MergeStrategy.strategy_keys
unless strategies.include?(merge.to_sym)
strategies = strategies.map { |k| "'#{k}'" }
raise _("The --merge option only accepts %{strategies}, or %{last_strategy}\n%{run_help}") % { strategies: strategies[0...-1].join(', '), last_strategy: strategies.last, run_help: RUN_HELP }
end
if merge == 'deep'
merge_options = { 'strategy' => 'deep',
'sort_merged_arrays' => !options[:sort_merged_arrays].nil?,
'merge_hash_arrays' => !options[:merge_hash_arrays].nil? }
if options[:prefix]
merge_options['knockout_prefix'] = options[:prefix]
end
else
merge_options = { 'strategy' => merge }
end
end
explain_data = !!options[:explain]
explain_options = !!options[:explain_options]
only_explain_options = explain_options && !explain_data
if keys.empty?
if only_explain_options
# Explain lookup_options for lookup of an unqualified value.
keys = Puppet::Pops::Lookup::GLOBAL
else
raise _('No keys were given to lookup.')
end
end
explain = explain_data || explain_options
# Format defaults to text (:s) when producing an explanation and :yaml when producing the value
format = options[:render_as] || (explain ? :s : :yaml)
renderer = Puppet::Network::FormatHandler.format(format)
raise _("Unknown rendering format '%{format}'") % { format: format } if renderer.nil?
generate_scope do |scope|
lookup_invocation = Puppet::Pops::Lookup::Invocation.new(scope, {}, {}, explain ? Puppet::Pops::Lookup::Explainer.new(explain_options, only_explain_options) : nil)
begin
type = options.include?(:type) ? Puppet::Pops::Types::TypeParser.singleton.parse(options[:type], scope) : nil
result = Puppet::Pops::Lookup.lookup(keys, type, options[:default_value], use_default_value, merge_options, lookup_invocation)
puts renderer.render(result) unless explain
rescue Puppet::DataBinding::LookupError => e
lookup_invocation.report_text { e.message }
exit(1) unless explain
end
puts format == :s ? lookup_invocation.explainer.explain : renderer.render(lookup_invocation.explainer.to_hash) if explain
end
exit(0)
end
def generate_scope
if options[:node]
node = options[:node]
else
node = Puppet[:node_name_value]
# If we want to lookup the node we are currently on
# we must returning these settings to their default values
Puppet.settings[:facts_terminus] = 'facter'
end
fact_file = options[:fact_file]
if fact_file
if fact_file.end_with?('.json')
given_facts = Puppet::Util::Json.load_file(fact_file)
elsif fact_file.end_with?('.yml', '.yaml')
given_facts = Puppet::Util::Yaml.safe_load_file(fact_file)
else
given_facts = Puppet::Util::Json.load_file_if_valid(fact_file)
given_facts ||= Puppet::Util::Yaml.safe_load_file_if_valid(fact_file)
end
unless given_facts.instance_of?(Hash)
raise _("Incorrectly formatted data in %{fact_file} given via the --facts flag (only accepts yaml and json files)") % { fact_file: fact_file }
end
if TRUSTED_INFORMATION_FACTS.any? { |key| given_facts.key? key }
unless TRUSTED_INFORMATION_FACTS.all? { |key| given_facts.key? key }
raise _("When overriding any of the %{trusted_facts_list} facts with %{fact_file} "\
"given via the --facts flag, they must all be overridden.") % { fact_file: fact_file, trusted_facts_list: TRUSTED_INFORMATION_FACTS.join(',') }
end
end
end
if node.is_a?(Puppet::Node)
node.add_extra_facts(given_facts) if given_facts
else # to allow unit tests to pass a node instance
facts = retrieve_node_facts(node, given_facts)
ni = Puppet::Node.indirection
tc = ni.terminus_class
if options[:compile]
if tc == :plain
node = ni.find(node, facts: facts, environment: Puppet[:environment])
else
begin
service = Puppet.runtime[:http]
session = service.create_session
cert = session.route_to(:ca)
_, x509 = cert.get_certificate(node)
cert = OpenSSL::X509::Certificate.new(x509)
Puppet::SSL::Oids.register_puppet_oids
trusted = Puppet::Context::TrustedInformation.remote(true, facts.values['certname'] || node, Puppet::SSL::Certificate.from_instance(cert))
Puppet.override(trusted_information: trusted) do
node = ni.find(node, facts: facts, environment: Puppet[:environment])
end
rescue
Puppet.warning _("CA is not available, the operation will continue without using trusted facts.")
node = ni.find(node, facts: facts, environment: Puppet[:environment])
end
end
else
ni.terminus_class = :plain
node = ni.find(node, facts: facts, environment: Puppet[:environment])
ni.terminus_class = tc
end
end
node.environment = Puppet[:environment] if Puppet.settings.set_by_cli?(:environment)
node.add_server_facts(Puppet::Node::ServerFacts.load)
Puppet[:code] = 'undef' unless options[:compile]
compiler = Puppet::Parser::Compiler.new(node)
if options[:node]
Puppet::Util.skip_external_facts do
compiler.compile { |catalog| yield(compiler.topscope); catalog }
end
else
compiler.compile { |catalog| yield(compiler.topscope); catalog }
end
end
def retrieve_node_facts(node, given_facts)
facts = Puppet::Node::Facts.indirection.find(node, :environment => Puppet.lookup(:current_environment))
facts = Puppet::Node::Facts.new(node, {}) if facts.nil?
facts.add_extra_values(given_facts) if given_facts
if facts.values.empty?
raise _("No facts available for target node: %{node}") % { node: node }
end
facts
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/application/device.rb | lib/puppet/application/device.rb | # frozen_string_literal: true
require_relative '../../puppet/application'
require_relative '../../puppet/configurer'
require_relative '../../puppet/util/network_device'
require_relative '../../puppet/ssl/oids'
class Puppet::Application::Device < Puppet::Application
run_mode :agent
attr_accessor :args, :agent, :host
def app_defaults
super.merge({
:catalog_terminus => :rest,
:catalog_cache_terminus => :json,
:node_terminus => :rest,
:facts_terminus => :network_device,
})
end
def preinit
# Do an initial trap, so that cancels don't get a stack trace.
Signal.trap(:INT) do
$stderr.puts _("Cancelling startup")
exit(0)
end
{
:apply => nil,
:waitforcert => nil,
:detailed_exitcodes => false,
:verbose => false,
:debug => false,
:centrallogs => false,
:setdest => false,
:resource => false,
:facts => false,
:target => nil,
:to_yaml => false,
}.each do |opt, val|
options[opt] = val
end
@args = {}
end
option("--centrallogging")
option("--debug", "-d")
option("--resource", "-r")
option("--facts", "-f")
option("--to_yaml", "-y")
option("--verbose", "-v")
option("--detailed-exitcodes") do |_arg|
options[:detailed_exitcodes] = true
end
option("--libdir LIBDIR") do |arg|
options[:libdir] = arg
end
option("--apply MANIFEST") do |arg|
options[:apply] = arg.to_s
end
option("--logdest DEST", "-l DEST") do |arg|
handle_logdest_arg(arg)
end
option("--waitforcert WAITFORCERT", "-w") do |arg|
options[:waitforcert] = arg.to_i
end
option("--port PORT", "-p") do |arg|
@args[:Port] = arg
end
option("--target DEVICE", "-t") do |arg|
options[:target] = arg.to_s
end
def summary
_("Manage remote network devices via OpenVox")
end
def help
<<~HELP
puppet-device(8) -- #{summary}
========
SYNOPSIS
--------
Retrieves catalogs from the OpenVox server and applies them to remote devices.
This subcommand can be run manually; or periodically using cron,
a scheduled task, or a similar tool.
USAGE
-----
puppet device [-h|--help] [-v|--verbose] [-d|--debug]
[-l|--logdest syslog|<file>|console] [--detailed-exitcodes]
[--deviceconfig <file>] [-w|--waitforcert <seconds>]
[--libdir <directory>]
[-a|--apply <file>] [-f|--facts] [-r|--resource <type> [name]]
[-t|--target <device>] [--user=<user>] [-V|--version]
DESCRIPTION
-----------
Devices require a proxy OpenVox agent to request certificates, collect facts,
retrieve and apply catalogs, and store reports.
USAGE NOTES
-----------
Devices managed by the puppet-device subcommand on an OpenVox agent are
configured in device.conf, which is located at $confdir/device.conf by default,
and is configurable with the $deviceconfig setting.
The device.conf file is an INI-like file, with one section per device:
[<DEVICE_CERTNAME>]
type <TYPE>
url <URL>
debug
The section name specifies the certname of the device.
The values for the type and url properties are specific to each type of device.
The optional debug property specifies transport-level debugging,
and is limited to telnet and ssh transports.
See https://puppet.com/docs/puppet/latest/config_file_device.html for details.
OPTIONS
-------
Note that any setting that's valid in the configuration file is also a valid
long argument. For example, 'server' is a valid configuration parameter, so
you can specify '--server <servername>' as an argument.
* --help, -h:
Print this help message
* --verbose, -v:
Turn on verbose reporting.
* --debug, -d:
Enable full debugging.
* --logdest, -l:
Where to send log messages. Choose between 'syslog' (the POSIX syslog
service), 'console', or the path to a log file. If debugging or verbosity is
enabled, this defaults to 'console'. Otherwise, it defaults to 'syslog'.
Multiple destinations can be set using a comma separated list
(eg: `/path/file1,console,/path/file2`)"
A path ending with '.json' will receive structured output in JSON format. The
log file will not have an ending ']' automatically written to it due to the
appending nature of logging. It must be appended manually to make the content
valid JSON.
* --detailed-exitcodes:
Provide transaction information via exit codes. If this is enabled, an exit
code of '1' means at least one device had a compile failure, an exit code of
'2' means at least one device had resource changes, and an exit code of '4'
means at least one device had resource failures. Exit codes of '3', '5', '6',
or '7' means that a bitwise combination of the preceding exit codes happened.
* --deviceconfig:
Path to the device config file for puppet device.
Default: $confdir/device.conf
* --waitforcert, -w:
This option only matters for targets that do not yet have certificates
and it is enabled by default, with a value of 120 (seconds). This causes
+puppet device+ to poll the server every 2 minutes and ask it to sign a
certificate request. This is useful for the initial setup of a target.
You can turn off waiting for certificates by specifying a time of 0.
* --libdir:
Override the per-device libdir with a local directory. Specifying a libdir also
disables pluginsync. This is useful for testing.
A path ending with '.jsonl' will receive structured output in JSON Lines
format.
* --apply:
Apply a manifest against a remote target. Target must be specified.
* --facts:
Displays the facts of a remote target. Target must be specified.
* --resource:
Displays a resource state as Puppet code, roughly equivalent to
`puppet resource`. Can be filtered by title. Requires --target be specified.
* --target:
Target a specific device/certificate in the device.conf. Doing so will perform a
device run against only that device/certificate.
* --to_yaml:
Output found resources in yaml format, suitable to use with Hiera and
create_resources.
* --user:
The user to run as.
EXAMPLE
-------
$ puppet device --target remotehost --verbose
AUTHOR
------
Brice Figureau
COPYRIGHT
---------
Copyright (c) 2011-2018 Puppet Inc.,
Copyright (c) 2024 Vox Pupuli
Licensed under the Apache 2.0 License
HELP
end
def main
if options[:resource] and !options[:target]
raise _("resource command requires target")
end
if options[:facts] and !options[:target]
raise _("facts command requires target")
end
unless options[:apply].nil?
raise _("missing argument: --target is required when using --apply") if options[:target].nil?
raise _("%{file} does not exist, cannot apply") % { file: options[:apply] } unless File.file?(options[:apply])
end
libdir = Puppet[:libdir]
vardir = Puppet[:vardir]
confdir = Puppet[:confdir]
ssldir = Puppet[:ssldir]
certname = Puppet[:certname]
env = Puppet::Node::Environment.remote(Puppet[:environment])
returns = Puppet.override(:current_environment => env, :loaders => Puppet::Pops::Loaders.new(env)) do
# find device list
require_relative '../../puppet/util/network_device/config'
devices = Puppet::Util::NetworkDevice::Config.devices.dup
if options[:target]
devices.select! { |key, _value| key == options[:target] }
end
if devices.empty?
if options[:target]
raise _("Target device / certificate '%{target}' not found in %{config}") % { target: options[:target], config: Puppet[:deviceconfig] }
else
Puppet.err _("No device found in %{config}") % { config: Puppet[:deviceconfig] }
exit(1)
end
end
devices.collect do |_devicename, device|
# TODO when we drop support for ruby < 2.5 we can remove the extra block here
device_url = URI.parse(device.url)
# Handle nil scheme & port
scheme = "#{device_url.scheme}://" if device_url.scheme
port = ":#{device_url.port}" if device_url.port
# override local $vardir and $certname
Puppet[:ssldir] = ::File.join(Puppet[:deviceconfdir], device.name, 'ssl')
Puppet[:confdir] = ::File.join(Puppet[:devicedir], device.name)
Puppet[:libdir] = options[:libdir] || ::File.join(Puppet[:devicedir], device.name, 'lib')
Puppet[:vardir] = ::File.join(Puppet[:devicedir], device.name)
Puppet[:certname] = device.name
ssl_context = nil
# create device directory under $deviceconfdir
Puppet::FileSystem.dir_mkpath(Puppet[:ssldir]) unless Puppet::FileSystem.dir_exist?(Puppet[:ssldir])
# this will reload and recompute default settings and create device-specific sub vardir
Puppet.settings.use :main, :agent, :ssl
# Workaround for PUP-8736: store ssl certs outside the cache directory to prevent accidental removal and keep the old path as symlink
optssldir = File.join(Puppet[:confdir], 'ssl')
Puppet::FileSystem.symlink(Puppet[:ssldir], optssldir) unless Puppet::FileSystem.exist?(optssldir)
unless options[:resource] || options[:facts] || options[:apply]
# Since it's too complicated to fix properly in the default settings, we workaround for PUP-9642 here.
# See https://github.com/puppetlabs/puppet/pull/7483#issuecomment-483455997 for details.
# This has to happen after `settings.use` above, so the directory is created and before `setup_host` below, where the SSL
# routines would fail with access errors
if Puppet.features.root? && !Puppet::Util::Platform.windows?
user = Puppet::Type.type(:user).new(name: Puppet[:user]).exists? ? Puppet[:user] : nil
group = Puppet::Type.type(:group).new(name: Puppet[:group]).exists? ? Puppet[:group] : nil
Puppet.debug("Fixing perms for #{user}:#{group} on #{Puppet[:confdir]}")
FileUtils.chown(user, group, Puppet[:confdir]) if user || group
end
ssl_context = setup_context
unless options[:libdir]
Puppet.override(ssl_context: ssl_context) do
Puppet::Configurer::PluginHandler.new.download_plugins(env) if Puppet::Configurer.should_pluginsync?
end
end
end
# this inits the device singleton, so that the facts terminus
# and the various network_device provider can use it
Puppet::Util::NetworkDevice.init(device)
if options[:resource]
type, name = parse_args(command_line.args)
Puppet.info _("retrieving resource: %{resource} from %{target} at %{scheme}%{url_host}%{port}%{url_path}") % { resource: type, target: device.name, scheme: scheme, url_host: device_url.host, port: port, url_path: device_url.path }
resources = find_resources(type, name)
if options[:to_yaml]
data = resources.map do |resource|
resource.prune_parameters(:parameters_to_include => @extra_params).to_hiera_hash
end.inject(:merge!)
text = YAML.dump(type.downcase => data)
else
text = resources.map do |resource|
resource.prune_parameters(:parameters_to_include => @extra_params).to_manifest.force_encoding(Encoding.default_external)
end.join("\n")
end
(puts text)
0
elsif options[:facts]
Puppet.info _("retrieving facts from %{target} at %{scheme}%{url_host}%{port}%{url_path}") % { resource: type, target: device.name, scheme: scheme, url_host: device_url.host, port: port, url_path: device_url.path }
remote_facts = Puppet::Node::Facts.indirection.find(name, :environment => env)
# Give a proper name to the facts
remote_facts.name = remote_facts.values['clientcert']
renderer = Puppet::Network::FormatHandler.format(:console)
puts renderer.render(remote_facts)
0
elsif options[:apply]
# avoid reporting to server
Puppet::Transaction::Report.indirection.terminus_class = :yaml
Puppet::Resource::Catalog.indirection.cache_class = nil
require_relative '../../puppet/application/apply'
begin
Puppet[:node_terminus] = :plain
Puppet[:catalog_terminus] = :compiler
Puppet[:catalog_cache_terminus] = nil
Puppet[:facts_terminus] = :network_device
Puppet.override(:network_device => true) do
Puppet::Application::Apply.new(Puppet::Util::CommandLine.new('puppet', ["apply", options[:apply]])).run_command
end
end
else
Puppet.info _("starting applying configuration to %{target} at %{scheme}%{url_host}%{port}%{url_path}") % { target: device.name, scheme: scheme, url_host: device_url.host, port: port, url_path: device_url.path }
overrides = {}
overrides[:ssl_context] = ssl_context if ssl_context
Puppet.override(overrides) do
configurer = Puppet::Configurer.new
configurer.run(:network_device => true, :pluginsync => false)
end
end
rescue => detail
Puppet.log_exception(detail)
# If we rescued an error, then we return 1 as the exit code
1
ensure
Puppet[:libdir] = libdir
Puppet[:vardir] = vardir
Puppet[:confdir] = confdir
Puppet[:ssldir] = ssldir
Puppet[:certname] = certname
end
end
if !returns or returns.compact.empty?
exit(1)
elsif options[:detailed_exitcodes]
# Bitwise OR the return codes together, puppet style
exit(returns.compact.reduce(:|))
elsif returns.include? 1
exit(1)
else
exit(0)
end
end
def parse_args(args)
type = args.shift or raise _("You must specify the type to display")
Puppet::Type.type(type) or raise _("Could not find type %{type}") % { type: type }
name = args.shift
[type, name]
end
def find_resources(type, name)
key = [type, name].join('/')
if name
[Puppet::Resource.indirection.find(key)]
else
Puppet::Resource.indirection.search(key, {})
end
end
def setup_context
waitforcert = options[:waitforcert] || (Puppet[:onetime] ? 0 : Puppet[:waitforcert])
sm = Puppet::SSL::StateMachine.new(waitforcert: waitforcert)
sm.ensure_client_certificate
end
def setup
setup_logs
Puppet::SSL::Oids.register_puppet_oids
# setup global device-specific defaults; creates all necessary directories, etc
Puppet.settings.use :main, :agent, :device, :ssl
if options[:apply] || options[:facts] || options[:resource]
Puppet::Util::Log.newdestination(:console)
else
args[:Server] = Puppet[:server]
if options[:centrallogs]
logdest = args[:Server]
logdest += ":" + args[:Port] if args.include?(:Port)
Puppet::Util::Log.newdestination(logdest)
end
Puppet::Transaction::Report.indirection.terminus_class = :rest
if Puppet[:catalog_cache_terminus]
Puppet::Resource::Catalog.indirection.cache_class = Puppet[:catalog_cache_terminus].intern
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/concurrent/thread_local_singleton.rb | lib/puppet/concurrent/thread_local_singleton.rb | # frozen_string_literal: true
module Puppet
module Concurrent
module ThreadLocalSingleton
def singleton
key = (name + ".singleton").intern
thread = Thread.current
value = thread.thread_variable_get(key)
if value.nil?
value = new
thread.thread_variable_set(key, value)
end
value
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/concurrent/synchronized.rb | lib/puppet/concurrent/synchronized.rb | # frozen_string_literal: true
module Puppet
module Concurrent
# Including Puppet::Concurrent::Synchronized into a class when running on JRuby
# causes all of its instance methods to be synchronized on the instance itself.
# When running on MRI it has no effect.
if RUBY_PLATFORM == 'java'
require 'jruby/synchronized'
Synchronized = JRuby::Synchronized
else
module Synchronized; end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/concurrent/lock.rb | lib/puppet/concurrent/lock.rb | # frozen_string_literal: true
require_relative '../../puppet/concurrent/synchronized'
module Puppet
module Concurrent
# A simple lock that at the moment only does any locking on jruby
class Lock
include Puppet::Concurrent::Synchronized
def synchronize
yield
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/scheduler/scheduler.rb | lib/puppet/scheduler/scheduler.rb | # frozen_string_literal: true
module Puppet::Scheduler
class Scheduler
def initialize(timer = Puppet::Scheduler::Timer.new)
@timer = timer
end
def run_loop(jobs)
mark_start_times(jobs, @timer.now)
until enabled(jobs).empty?
@timer.wait_for(min_interval_to_next_run_from(jobs, @timer.now))
run_ready(jobs, @timer.now)
end
end
private
def enabled(jobs)
jobs.select(&:enabled?)
end
def mark_start_times(jobs, start_time)
jobs.each do |job|
job.start_time = start_time
end
end
def min_interval_to_next_run_from(jobs, from_time)
enabled(jobs).map do |j|
j.interval_to_next_from(from_time)
end.min
end
def run_ready(jobs, at_time)
enabled(jobs).each do |j|
# This check intentionally happens right before each run,
# instead of filtering on ready schedulers, since one may adjust
# the readiness of a later one
if j.ready?(at_time)
j.run(at_time)
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/scheduler/splay_job.rb | lib/puppet/scheduler/splay_job.rb | # frozen_string_literal: true
module Puppet::Scheduler
class SplayJob < Job
attr_reader :splay, :splay_limit
def initialize(run_interval, splay_limit, &block)
@splay, @splay_limit = calculate_splay(splay_limit)
super(run_interval, &block)
end
def interval_to_next_from(time)
if last_run
super
else
(start_time + splay) - time
end
end
def ready?(time)
if last_run
super
else
start_time + splay <= time
end
end
# Recalculates splay.
#
# @param splay_limit [Integer] the maximum time (in seconds) to delay before an agent's first run.
# @return @splay [Integer] a random integer less than or equal to the splay limit that represents the seconds to
# delay before next agent run.
def splay_limit=(splay_limit)
if @splay_limit != splay_limit
@splay, @splay_limit = calculate_splay(splay_limit)
end
end
private
def calculate_splay(limit)
[rand(limit + 1), limit]
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/scheduler/timer.rb | lib/puppet/scheduler/timer.rb | # frozen_string_literal: true
module Puppet::Scheduler
class Timer
def wait_for(seconds)
if seconds > 0
sleep(seconds)
end
end
def now
Time.now
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.