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
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/type_definition_instantiator.rb
lib/puppet/pops/loader/type_definition_instantiator.rb
# frozen_string_literal: true # The TypeDefinitionInstantiator instantiates a type alias or a type definition # module Puppet::Pops module Loader class TypeDefinitionInstantiator def self.create(loader, typed_name, source_ref, pp_code_string) # parse and validate parser = Parser::EvaluatingParser.new() model = parser.parse_string(pp_code_string, source_ref) # Only one type is allowed (and no other definitions) name = typed_name.name case model.definitions.size when 0 raise ArgumentError, _("The code loaded from %{source_ref} does not define the type '%{name}' - it is empty.") % { source_ref: source_ref, name: name } when 1 # ok else raise ArgumentError, _("The code loaded from %{source_ref} must contain only the type '%{name}' - it has additional definitions.") % { source_ref: source_ref, name: name } end type_definition = model.definitions[0] unless type_definition.is_a?(Model::TypeAlias) || type_definition.is_a?(Model::TypeDefinition) raise ArgumentError, _("The code loaded from %{source_ref} does not define the type '%{name}' - no type alias or type definition found.") % { source_ref: source_ref, name: name } end actual_name = type_definition.name unless name == actual_name.downcase raise ArgumentError, _("The code loaded from %{source_ref} produced type with the wrong name, expected '%{name}', actual '%{actual_name}'") % { source_ref: source_ref, name: name, actual_name: actual_name } end unless model.body == type_definition raise ArgumentError, _("The code loaded from %{source_ref} contains additional logic - can only contain the type '%{name}'") % { source_ref: source_ref, name: name } end # Adapt the type definition with loader - this is used from logic contained in its body to find the # loader to use when resolving contained aliases API. Such logic have a hard time finding the closure (where # the loader is known - hence this mechanism private_loader = loader.private_loader Adapters::LoaderAdapter.adapt(type_definition).loader_name = private_loader.loader_name create_runtime_type(type_definition) end def self.create_from_model(type_definition, loader) typed_name = TypedName.new(:type, type_definition.name) type = create_runtime_type(type_definition) loader.set_entry( typed_name, type, type_definition.locator.to_uri(type_definition) ) type end # @api private def self.create_runtime_type(type_definition) # Using the RUNTIME_NAME_AUTHORITY as the name_authority is motivated by the fact that the type # alias name (managed by the runtime) becomes the name of the created type # create_type(type_definition.name, type_definition.type_expr, Pcore::RUNTIME_NAME_AUTHORITY) end # @api private def self.create_type(name, type_expr, name_authority) create_named_type(name, named_definition(type_expr), type_expr, name_authority) end # @api private def self.create_named_type(name, type_name, type_expr, name_authority) case type_name when 'Object' # No need for an alias. The Object type itself will receive the name instead unless type_expr.is_a?(Model::LiteralHash) type_expr = type_expr.keys.empty? ? nil : type_expr.keys[0] unless type_expr.is_a?(Hash) end Types::PObjectType.new(name, type_expr) when 'TypeSet' # No need for an alias. The Object type itself will receive the name instead type_expr = type_expr.keys.empty? ? nil : type_expr.keys[0] unless type_expr.is_a?(Hash) Types::PTypeSetType.new(name, type_expr, name_authority) else Types::PTypeAliasType.new(name, type_expr) end end # @api private def self.named_definition(te) return 'Object' if te.is_a?(Model::LiteralHash) te.is_a?(Model::AccessExpression) && (left = te.left_expr).is_a?(Model::QualifiedReference) ? left.cased_value : nil end def several_paths? false end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/runtime3_type_loader.rb
lib/puppet/pops/loader/runtime3_type_loader.rb
# frozen_string_literal: true module Puppet::Pops module Loader # Runtime3TypeLoader # === # Loads a resource type using the 3.x type loader # # @api private class Runtime3TypeLoader < BaseLoader attr_reader :resource_3x_loader def initialize(parent_loader, loaders, environment, resource_3x_loader) super(parent_loader, environment.name, environment) @environment = environment @resource_3x_loader = resource_3x_loader end def discover(type, error_collector = nil, name_authority = Pcore::RUNTIME_NAME_AUTHORITY, &block) # TODO: Use generated index of all known types (requires separate utility). parent.discover(type, error_collector, name_authority, &block) end def to_s "(Runtime3TypeLoader '#{loader_name()}')" end # Finds typed/named entity in this module # @param typed_name [TypedName] the type/name to find # @return [Loader::NamedEntry, nil found/created entry, or nil if not found # def find(typed_name) return nil unless typed_name.name_authority == Pcore::RUNTIME_NAME_AUTHORITY case typed_name.type when :type value = nil name = typed_name.name if @resource_3x_loader.nil? value = Puppet::Type.type(name) unless typed_name.qualified? if value.nil? # Look for a user defined type value = @environment.known_resource_types.find_definition(name) end else impl_te = find_impl(TypedName.new(:resource_type_pp, name, typed_name.name_authority)) value = impl_te.value unless impl_te.nil? end if value.nil? # Cache the fact that it wasn't found set_entry(typed_name, nil) return nil end # Loaded types doesn't have the same life cycle as this loader, so we must start by # checking if the type was created. If it was, an entry will already be stored in # this loader. If not, then it was created before this loader was instantiated and # we must therefore add it. te = get_entry(typed_name) te = set_entry(typed_name, Types::TypeFactory.resource(value.name.to_s)) if te.nil? || te.value.nil? te when :resource_type_pp @resource_3x_loader.nil? ? nil : find_impl(typed_name) else nil end end # Find the implementation for the resource type by first consulting the internal loader for pp defined 'Puppet::Resource::ResourceType3' # instances, then check for a Puppet::Type and lastly check for a defined type. # def find_impl(typed_name) name = typed_name.name te = StaticLoader::BUILTIN_TYPE_NAMES_LC.include?(name) ? nil : @resource_3x_loader.load_typed(typed_name) if te.nil? || te.value.nil? # Look for Puppet::Type value = Puppet::Type.type(name) unless typed_name.qualified? if value.nil? # Look for a user defined type value = @environment.known_resource_types.find_definition(name) if value.nil? # Cache the fact that it wasn't found @resource_3x_loader.set_entry(typed_name, nil) return nil end end te = @resource_3x_loader.get_entry(typed_name) te = @resource_3x_loader.set_entry(typed_name, value) if te.nil? || te.value.nil? end te end private :find_impl # Allows shadowing since this loader is populated with all loaded resource types at time # of loading. This loading will, for built in types override the aliases configured in the static # loader. # def allow_shadowing? true end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/base_loader.rb
lib/puppet/pops/loader/base_loader.rb
# frozen_string_literal: true module Puppet::Pops module Loader # BaseLoader # === # An abstract implementation of Loader # # A derived class should implement `find(typed_name)` and set entries, and possible handle "miss caching". # # @api private # class BaseLoader < Loader # The parent loader attr_reader :parent def initialize(parent_loader, loader_name, environment) super(loader_name, environment) @parent = parent_loader # the higher priority loader to consult @named_values = {} # hash name => NamedEntry @last_result = nil # the value of the last name (optimization) end def discover(type, error_collector = nil, name_authority = Pcore::RUNTIME_NAME_AUTHORITY, &block) result = [] @named_values.each_pair do |key, entry| result << key unless entry.nil? || entry.value.nil? || key.type != type || (block_given? && !yield(key)) end result.concat(parent.discover(type, error_collector, name_authority, &block)) result.uniq! result end # @api public # def load_typed(typed_name) # The check for "last queried name" is an optimization when a module searches. First it checks up its parent # chain, then itself, and then delegates to modules it depends on. # These modules are typically parented by the same # loader as the one initiating the search. It is inefficient to again try to search the same loader for # the same name. synchronize do if @last_result.nil? || typed_name != @last_result.typed_name @last_result = internal_load(typed_name) else @last_result end end end # @api public # def loaded_entry(typed_name, check_dependencies = false) synchronize do if @named_values.has_key?(typed_name) @named_values[typed_name] elsif parent parent.loaded_entry(typed_name, check_dependencies) else nil end end end # This method is final (subclasses should not override it) # # @api private # def get_entry(typed_name) @named_values[typed_name] end # @api private # def set_entry(typed_name, value, origin = nil) synchronize do # It is never ok to redefine in the very same loader unless redefining a 'not found' entry = @named_values[typed_name] if entry fail_redefine(entry) unless entry.value.nil? end # Check if new entry shadows existing entry and fail # (unless special loader allows shadowing) if typed_name.type == :type && !allow_shadowing? entry = loaded_entry(typed_name) if entry fail_redefine(entry) unless entry.value.nil? # || entry.value == value end end @last_result = Loader::NamedEntry.new(typed_name, value, origin) @named_values[typed_name] = @last_result end end # @api private # def add_entry(type, name, value, origin) set_entry(TypedName.new(type, name), value, origin) end # @api private # def remove_entry(typed_name) synchronize do unless @named_values.delete(typed_name).nil? @last_result = nil unless @last_result.nil? || typed_name != @last_result.typed_name end end end # Promotes an already created entry (typically from another loader) to this loader # # @api private # def promote_entry(named_entry) synchronize do typed_name = named_entry.typed_name entry = @named_values[typed_name] if entry then fail_redefine(entry); end @named_values[typed_name] = named_entry end end protected def allow_shadowing? false end private def fail_redefine(entry) origin_info = entry.origin ? _("Originally set %{original}.") % { original: origin_label(entry.origin) } : _("Set at unknown location") raise ArgumentError, _("Attempt to redefine entity '%{name}'. %{origin_info}") % { name: entry.typed_name, origin_info: origin_info } end # TODO: Should not really be here?? - TODO: A Label provider ? semantics for the URI? # def origin_label(origin) if origin && origin.is_a?(URI) format_uri(origin) elsif origin.respond_to?(:uri) format_uri(origin.uri) else origin end end def format_uri(uri) (uri.scheme == 'puppet' ? 'by ' : 'at ') + uri.to_s.sub(/^puppet:/, '') end # loads in priority order: # 1. already loaded here # 2. load from parent # 3. find it here # 4. give up # def internal_load(typed_name) # avoid calling get_entry by looking it up te = @named_values[typed_name] return te unless te.nil? || te.value.nil? te = parent.load_typed(typed_name) return te unless te.nil? || te.value.nil? # Under some circumstances, the call to the parent loader will have resulted in files being # parsed that in turn contained references to the requested entity and hence, caused a # recursive call into this loader. This means that the entry might be present now, so a new # check must be made. te = @named_values[typed_name] te.nil? || te.value.nil? ? find(typed_name) : te end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/ruby_function_instantiator.rb
lib/puppet/pops/loader/ruby_function_instantiator.rb
# frozen_string_literal: true # The RubyFunctionInstantiator instantiates a Puppet::Functions::Function given the ruby source # that calls Puppet::Functions.create_function. # class Puppet::Pops::Loader::RubyFunctionInstantiator # Produces an instance of the Function class with the given typed_name, or fails with an error if the # given ruby source does not produce this instance when evaluated. # # @param loader [Puppet::Pops::Loader::Loader] The loader the function is associated with # @param typed_name [Puppet::Pops::Loader::TypedName] the type / name of the function to load # @param source_ref [URI, String] a reference to the source / origin of the ruby code to evaluate # @param ruby_code_string [String] ruby code in a string # # @return [Puppet::Pops::Functions.Function] - an instantiated function with global scope closure associated with the given loader # def self.create(loader, typed_name, source_ref, ruby_code_string) unless ruby_code_string.is_a?(String) && ruby_code_string =~ /Puppet::Functions\.create_function/ raise ArgumentError, _("The code loaded from %{source_ref} does not seem to be a Puppet 4x API function - no create_function call.") % { source_ref: source_ref } end # make the private loader available in a binding to allow it to be passed on loader_for_function = loader.private_loader here = get_binding(loader_for_function) created = eval(ruby_code_string, here, source_ref, 1) # rubocop:disable Security/Eval unless created.is_a?(Class) raise ArgumentError, _("The code loaded from %{source_ref} did not produce a Function class when evaluated. Got '%{klass}'") % { source_ref: source_ref, klass: created.class } end unless created.name.to_s == typed_name.name() raise ArgumentError, _("The code loaded from %{source_ref} produced mis-matched name, expected '%{type_name}', got %{created_name}") % { source_ref: source_ref, type_name: typed_name.name, created_name: created.name } end # create the function instance - it needs closure (scope), and loader (i.e. where it should start searching for things # when calling functions etc. # It should be bound to global scope # Sets closure scope to nil, to let it be picked up at runtime from Puppet.lookup(:global_scope) # If function definition used the loader from the binding to create a new loader, that loader wins created.new(nil, loader_for_function) end # Produces a binding where the given loader is bound as a local variable (loader_injected_arg). This variable can be used in loaded # ruby code - e.g. to call Puppet::Function.create_loaded_function(:name, loader,...) # def self.get_binding(loader_injected_arg) binding end private_class_method :get_binding end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/predefined_loader.rb
lib/puppet/pops/loader/predefined_loader.rb
# frozen_string_literal: true module Puppet::Pops::Loader # A PredefinedLoader is a loader that is manually populated with loaded elements # before being used. It never loads anything on its own. # class PredefinedLoader < BaseLoader def find(typed_name) nil end def to_s "(PredefinedLoader '#{loader_name}')" end # Allows shadowing since this loader is used internally for things like function local types # And they should win as there is otherwise a risk that the local types clash with built in types # that were added after the function was written, or by resource types loaded by the 3x auto loader. # def allow_shadowing? true end def synchronize(&block) yield end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/uri_helper.rb
lib/puppet/pops/loader/uri_helper.rb
# frozen_string_literal: true module Puppet::Pops::Loader::UriHelper # Raises an exception if specified gem can not be located # def path_for_uri(uri, subdir = 'lib') case uri.scheme when "gem" begin spec = Gem::Specification.find_by_name(uri.hostname) # if path given append that, else append given subdir File.join(spec.gem_dir, uri.path.empty?() ? subdir : uri.path) rescue StandardError => e raise "TODO TYPE: Failed to located gem #{uri}. #{e.message}" end when "file" File.join(uri.path, subdir) when nil File.join(uri.path, subdir) else raise "Not a valid scheme for a loader: #{uri.scheme}. Use a 'file:' (or just a path), or 'gem://gemname[/path]" end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/typed_name.rb
lib/puppet/pops/loader/typed_name.rb
# frozen_string_literal: true module Puppet::Pops module Loader # A namespace/name/type combination that can be used as a compound hash key # # @api public class TypedName attr_reader :hash attr_reader :type attr_reader :name_authority attr_reader :name attr_reader :name_parts attr_reader :compound_name def initialize(type, name, name_authority = Pcore::RUNTIME_NAME_AUTHORITY) name = name.downcase @type = type @name_authority = name_authority # relativize the name (get rid of leading ::), and make the split string available parts = name.to_s.split(DOUBLE_COLON) if parts[0].empty? parts.shift @name = name[2..] else @name = name end @name_parts = parts.freeze # Use a frozen compound key for the hash and comparison. Most varying part first @compound_name = "#{@name}/#{@type}/#{@name_authority}" @hash = @compound_name.hash freeze end def ==(o) o.class == self.class && o.compound_name == @compound_name end alias eql? == # @return the parent of this instance, or nil if this instance is not qualified def parent @name_parts.size > 1 ? self.class.new(@type, @name_parts[0...-1].join(DOUBLE_COLON), @name_authority) : nil end def qualified? @name_parts.size > 1 end def to_s "#{@name_authority}/#{@type}/#{@name}" end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/ruby_legacy_function_instantiator.rb
lib/puppet/pops/loader/ruby_legacy_function_instantiator.rb
# frozen_string_literal: true # The RubyLegacyFunctionInstantiator instantiates a Puppet::Functions::Function given the ruby source # that calls Puppet::Functions.create_function. # require 'ripper' class Puppet::Pops::Loader::RubyLegacyFunctionInstantiator UNKNOWN = '<unknown>' # Produces an instance of the Function class with the given typed_name, or fails with an error if the # given ruby source does not produce this instance when evaluated. # # @param loader [Puppet::Pops::Loader::Loader] The loader the function is associated with # @param typed_name [Puppet::Pops::Loader::TypedName] the type / name of the function to load # @param source_ref [URI, String] a reference to the source / origin of the ruby code to evaluate # @param ruby_code_string [String] ruby code in a string # # @return [Puppet::Pops::Functions.Function] - an instantiated function with global scope closure associated with the given loader # def self.create(loader, typed_name, source_ref, ruby_code_string) # Assert content of 3x function by parsing assertion_result = [] if assert_code(ruby_code_string, source_ref, assertion_result) unless ruby_code_string.is_a?(String) && assertion_result.include?(:found_newfunction) raise ArgumentError, _("The code loaded from %{source_ref} does not seem to be a Puppet 3x API function - no 'newfunction' call.") % { source_ref: source_ref } end end # make the private loader available in a binding to allow it to be passed on loader_for_function = loader.private_loader here = get_binding(loader_for_function) # Avoid reloading the function if already loaded via one of the APIs that trigger 3x function loading # Check if function is already loaded the 3x way (and obviously not the 4x way since we would not be here in the # first place. environment = Puppet.lookup(:current_environment) func_info = Puppet::Parser::Functions.environment_module(environment).get_function_info(typed_name.name.to_sym) if func_info.nil? # This will do the 3x loading and define the "function_<name>" and "real_function_<name>" methods # in the anonymous module used to hold function definitions. # func_info = eval(ruby_code_string, here, source_ref, 1) # rubocop:disable Security/Eval # Validate what was loaded unless func_info.is_a?(Hash) # TRANSLATORS - the word 'newfunction' should not be translated as it is a method name. raise ArgumentError, _("Illegal legacy function definition! The code loaded from %{source_ref} did not return the result of calling 'newfunction'. Got '%{klass}'") % { source_ref: source_ref, klass: func_info.class } end unless func_info[:name] == "function_#{typed_name.name()}" raise ArgumentError, _("The code loaded from %{source_ref} produced mis-matched name, expected 'function_%{type_name}', got '%{created_name}'") % { source_ref: source_ref, type_name: typed_name.name, created_name: func_info[:name] } end end created = Puppet::Functions::Function3x.create_function(typed_name.name(), func_info, loader_for_function) # create the function instance - it needs closure (scope), and loader (i.e. where it should start searching for things # when calling functions etc. # It should be bound to global scope # Sets closure scope to nil, to let it be picked up at runtime from Puppet.lookup(:global_scope) # If function definition used the loader from the binding to create a new loader, that loader wins created.new(nil, loader_for_function) end # Produces a binding where the given loader is bound as a local variable (loader_injected_arg). This variable can be used in loaded # ruby code - e.g. to call Puppet::Function.create_loaded_function(:name, loader,...) # def self.get_binding(loader_injected_arg) binding end private_class_method :get_binding def self.assert_code(code_string, source_ref, result) ripped = Ripper.sexp(code_string) return false if ripped.nil? # Let the next real parse crash and tell where and what is wrong ripped.each { |x| walk(x, source_ref, result) } true end private_class_method :assert_code def self.walk(x, source_ref, result) return unless x.is_a?(Array) first = x[0] case first when :fcall, :call # Ripper returns a :fcall for a function call in a module (want to know there is a call to newfunction()). # And it returns :call for a qualified named call identity_part = find_identity(x) result << :found_newfunction if identity_part.is_a?(Array) && identity_part[1] == 'newfunction' when :def, :defs # There should not be any calls to def in a 3x function mname, mline = extract_name_line(find_identity(x)) raise SecurityError, _("Illegal method definition of method '%{method_name}' in source %{source_ref} on line %{line} in legacy function. See %{url} for more information") % { method_name: mname, source_ref: source_ref, line: mline, url: "https://puppet.com/docs/puppet/latest/functions_refactor_legacy.html" } end x.each { |v| walk(v, source_ref, result) } end private_class_method :walk def self.find_identity(rast) rast.find { |x| x.is_a?(Array) && x[0] == :@ident } end private_class_method :find_identity # Extracts the method name and line number from the Ripper Rast for an id entry. # The expected input (a result from Ripper :@ident entry) is an array with: # [0] == :def (or :defs for self.def) # [1] == method name # [2] == [ <filename>, <linenumber> ] # # Returns an Array; a tuple with method name and line number or "<unknown>" if either is missing, or format is not the expected # def self.extract_name_line(x) (if x.is_a?(Array) [x[1], x[2].is_a?(Array) ? x[2][1] : nil] else [nil, nil] end).map { |v| v.nil? ? UNKNOWN : v } end private_class_method :extract_name_line end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/model/model_tree_dumper.rb
lib/puppet/pops/model/model_tree_dumper.rb
# frozen_string_literal: true # Dumps a Pops::Model in reverse polish notation; i.e. LISP style # The intention is to use this for debugging output # TODO: BAD NAME - A DUMP is a Ruby Serialization # class Puppet::Pops::Model::ModelTreeDumper < Puppet::Pops::Model::TreeDumper def dump_Array o o.collect { |e| do_dump(e) } end def dump_LiteralFloat o o.value.to_s end def dump_LiteralInteger o case o.radix when 10 o.value.to_s when 8 "0%o" % o.value when 16 "0x%X" % o.value else "bad radix:" + o.value.to_s end end def dump_LiteralValue o o.value.to_s end def dump_QualifiedReference o o.cased_value.to_s end def dump_Factory o o['locator'] ||= Puppet::Pops::Parser::Locator.locator("<not from source>", nil) do_dump(o.model) end def dump_ArithmeticExpression o [o.operator.to_s, do_dump(o.left_expr), do_dump(o.right_expr)] end # x[y] prints as (slice x y) def dump_AccessExpression o if o.keys.size <= 1 ["slice", do_dump(o.left_expr), do_dump(o.keys[0])] else ["slice", do_dump(o.left_expr), do_dump(o.keys)] end end def dump_MatchesExpression o [o.operator.to_s, do_dump(o.left_expr), do_dump(o.right_expr)] end def dump_CollectExpression o result = ["collect", do_dump(o.type_expr), :indent, :break, do_dump(o.query), :indent] o.operations do |ao| result << :break << do_dump(ao) end result += [:dedent, :dedent] result end def dump_EppExpression o result = ["epp"] # result << ["parameters"] + o.parameters.collect {|p| do_dump(p) } if o.parameters.size() > 0 if o.body result << do_dump(o.body) else result << [] end result end def dump_ExportedQuery o result = ["<<| |>>"] result += dump_QueryExpression(o) unless is_nop?(o.expr) result end def dump_VirtualQuery o result = ["<| |>"] result += dump_QueryExpression(o) unless is_nop?(o.expr) result end def dump_QueryExpression o [do_dump(o.expr)] end def dump_ComparisonExpression o [o.operator.to_s, do_dump(o.left_expr), do_dump(o.right_expr)] end def dump_AndExpression o ["&&", do_dump(o.left_expr), do_dump(o.right_expr)] end def dump_OrExpression o ["||", do_dump(o.left_expr), do_dump(o.right_expr)] end def dump_InExpression o ["in", do_dump(o.left_expr), do_dump(o.right_expr)] end def dump_AssignmentExpression o [o.operator.to_s, do_dump(o.left_expr), do_dump(o.right_expr)] end # Produces (name => expr) or (name +> expr) def dump_AttributeOperation o [o.attribute_name, o.operator, do_dump(o.value_expr)] end def dump_AttributesOperation o ['* =>', do_dump(o.expr)] end def dump_LiteralList o ["[]"] + o.values.collect { |x| do_dump(x) } end def dump_LiteralHash o ["{}"] + o.entries.collect { |x| do_dump(x) } end def dump_KeyedEntry o [do_dump(o.key), do_dump(o.value)] end def dump_MatchExpression o [o.operator.to_s, do_dump(o.left_expr), do_dump(o.right_expr)] end def dump_LiteralString o "'#{o.value}'" end def dump_LambdaExpression o result = ["lambda"] result << ["parameters"] + o.parameters.collect { |p| do_dump(p) } if o.parameters.size() > 0 result << ['return_type', do_dump(o.return_type)] unless o.return_type.nil? if o.body result << do_dump(o.body) else result << [] end result end def dump_LiteralDefault o ":default" end def dump_LiteralUndef o ":undef" end def dump_LiteralRegularExpression o Puppet::Pops::Types::StringConverter.convert(o.value, '%p') end def dump_Nop o ":nop" end def dump_NamedAccessExpression o [".", do_dump(o.left_expr), do_dump(o.right_expr)] end def dump_NilClass o "()" end def dump_NotExpression o ['!', dump(o.expr)] end def dump_VariableExpression o "$#{dump(o.expr)}" end # Interpolation (to string) shown as (str expr) def dump_TextExpression o ["str", do_dump(o.expr)] end def dump_UnaryMinusExpression o ['-', do_dump(o.expr)] end def dump_UnfoldExpression o ['unfold', do_dump(o.expr)] end def dump_BlockExpression o result = ["block", :indent] o.statements.each { |x| result << :break; result << do_dump(x) } result << :dedent << :break result end # Interpolated strings are shown as (cat seg0 seg1 ... segN) def dump_ConcatenatedString o ["cat"] + o.segments.collect { |x| do_dump(x) } end def dump_HeredocExpression(o) ["@(#{o.syntax})", :indent, :break, do_dump(o.text_expr), :dedent, :break] end def dump_HostClassDefinition o result = ["class", o.name] result << ["inherits", o.parent_class] if o.parent_class result << ["parameters"] + o.parameters.collect { |p| do_dump(p) } if o.parameters.size() > 0 if o.body result << do_dump(o.body) else result << [] end result end def dump_PlanDefinition o result = ["plan", o.name] result << ["parameters"] + o.parameters.collect { |p| do_dump(p) } if o.parameters.size() > 0 if o.body result << do_dump(o.body) else result << [] end result end def dump_NodeDefinition o result = ["node"] result << ["matches"] + o.host_matches.collect { |m| do_dump(m) } result << ["parent", do_dump(o.parent)] if o.parent if o.body result << do_dump(o.body) else result << [] end result end def dump_NamedDefinition o # the nil must be replaced with a string result = [nil, o.name] result << ["parameters"] + o.parameters.collect { |p| do_dump(p) } if o.parameters.size() > 0 if o.body result << do_dump(o.body) else result << [] end result end def dump_FunctionDefinition o result = ['function', o.name] result << ['parameters'] + o.parameters.collect { |p| do_dump(p) } if o.parameters.size() > 0 result << ['return_type', do_dump(o.return_type)] unless o.return_type.nil? if o.body result << do_dump(o.body) else result << [] end result end def dump_ResourceTypeDefinition o result = dump_NamedDefinition(o) result[0] = 'define' result end def dump_ResourceOverrideExpression o form = o.form == 'regular' ? '' : o.form + '-' result = [form + 'override', do_dump(o.resources), :indent] o.operations.each do |p| result << :break << do_dump(p) end result << :dedent result end def dump_ReservedWord o ['reserved', o.word] end # Produces parameters as name, or (= name value) def dump_Parameter o name_prefix = o.captures_rest ? '*' : '' name_part = "#{name_prefix}#{o.name}" if o.value && o.type_expr ["=t", do_dump(o.type_expr), name_part, do_dump(o.value)] elsif o.value ["=", name_part, do_dump(o.value)] elsif o.type_expr ["t", do_dump(o.type_expr), name_part] else name_part end end def dump_ParenthesizedExpression o do_dump(o.expr) end # Hides that Program exists in the output (only its body is shown), the definitions are just # references to contained classes, resource types, and nodes def dump_Program(o) dump(o.body) end def dump_IfExpression o result = ["if", do_dump(o.test), :indent, :break, ["then", :indent, do_dump(o.then_expr), :dedent]] result += [:break, ["else", :indent, do_dump(o.else_expr), :dedent], :dedent] unless is_nop? o.else_expr result end def dump_UnlessExpression o result = ["unless", do_dump(o.test), :indent, :break, ["then", :indent, do_dump(o.then_expr), :dedent]] result += [:break, ["else", :indent, do_dump(o.else_expr), :dedent], :dedent] unless is_nop? o.else_expr result end # Produces (invoke name args...) when not required to produce an rvalue, and # (call name args ... ) otherwise. # def dump_CallNamedFunctionExpression o result = [o.rval_required ? "call" : "invoke", do_dump(o.functor_expr)] o.arguments.collect { |a| result << do_dump(a) } result << do_dump(o.lambda) if o.lambda result end # def dump_CallNamedFunctionExpression o # result = [o.rval_required ? "call" : "invoke", do_dump(o.functor_expr)] # o.arguments.collect {|a| result << do_dump(a) } # result # end def dump_CallMethodExpression o result = [o.rval_required ? "call-method" : "invoke-method", do_dump(o.functor_expr)] o.arguments.collect { |a| result << do_dump(a) } result << do_dump(o.lambda) if o.lambda result end def dump_CaseExpression o result = ["case", do_dump(o.test), :indent] o.options.each do |s| result << :break << do_dump(s) end result << :dedent end def dump_CaseOption o result = ["when"] result << o.values.collect { |x| do_dump(x) } result << ["then", do_dump(o.then_expr)] result end def dump_RelationshipExpression o [o.operator.to_s, do_dump(o.left_expr), do_dump(o.right_expr)] end def dump_RenderStringExpression o ["render-s", " '#{o.value}'"] end def dump_RenderExpression o ["render", do_dump(o.expr)] end def dump_ResourceBody o result = [do_dump(o.title), :indent] o.operations.each do |p| result << :break << do_dump(p) end result << :dedent result end def dump_ResourceDefaultsExpression o form = o.form == 'regular' ? '' : o.form + '-' result = [form + 'resource-defaults', do_dump(o.type_ref), :indent] o.operations.each do |p| result << :break << do_dump(p) end result << :dedent result end def dump_ResourceExpression o form = o.form == 'regular' ? '' : o.form + '-' result = [form + 'resource', do_dump(o.type_name), :indent] o.bodies.each do |b| result << :break << do_dump(b) end result << :dedent result end def dump_SelectorExpression o ["?", do_dump(o.left_expr)] + o.selectors.collect { |x| do_dump(x) } end def dump_SelectorEntry o [do_dump(o.matching_expr), "=>", do_dump(o.value_expr)] end def dump_TypeAlias(o) ['type-alias', o.name, do_dump(o.type_expr)] end def dump_TypeMapping(o) ['type-mapping', do_dump(o.type_expr), do_dump(o.mapping_expr)] end def dump_TypeDefinition(o) ['type-definition', o.name, o.parent, do_dump(o.body)] end def dump_Object o [o.class.to_s, o.to_s] end def is_nop? o o.nil? || o.is_a?(Puppet::Pops::Model::Nop) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/model/tree_dumper.rb
lib/puppet/pops/model/tree_dumper.rb
# frozen_string_literal: true # Base class for formatted textual dump of a "model" # class Puppet::Pops::Model::TreeDumper attr_accessor :indent_count def initialize initial_indentation = 0 @@dump_visitor ||= Puppet::Pops::Visitor.new(nil, "dump", 0, 0) @indent_count = initial_indentation end def dump(o) format(do_dump(o)) end def do_dump(o) @@dump_visitor.visit_this_0(self, o) end def indent " " * indent_count end def format(x) result = ''.dup parts = format_r(x) parts.each_index do |i| if i > 0 # separate with space unless previous ends with whitespace or ( result << ' ' if parts[i] != ")" && parts[i - 1] !~ /.*(?:\s+|\()$/ && parts[i] !~ /^\s+/ end result << parts[i].to_s end result end def format_r(x) result = [] case x when :break result << "\n" + indent when :indent @indent_count += 1 when :dedent @indent_count -= 1 when Array result << '(' result += x.collect { |a| format_r(a) }.flatten result << ')' when Symbol result << x.to_s # Allows Symbols in arrays e.g. ["text", =>, "text"] else result << x end result end def is_nop? o o.nil? || o.is_a?(Puppet::Pops::Model::Nop) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/model/ast_transformer.rb
lib/puppet/pops/model/ast_transformer.rb
# frozen_string_literal: true require_relative '../../../puppet/parser/ast' # The receiver of `import(file)` calls; once per imported file, or nil if imports are ignored # # Transforms a Pops::Model to classic Puppet AST. # TODO: Documentation is currently skipped completely (it is only used for Rdoc) # class Puppet::Pops::Model::AstTransformer AST = Puppet::Parser::AST Model = Puppet::Pops::Model attr_reader :importer def initialize(source_file = "unknown-file", importer = nil) @@transform_visitor ||= Puppet::Pops::Visitor.new(nil, "transform", 0, 0) @@query_transform_visitor ||= Puppet::Pops::Visitor.new(nil, "query", 0, 0) @@hostname_transform_visitor ||= Puppet::Pops::Visitor.new(nil, "hostname", 0, 0) @importer = importer @source_file = source_file end # Initialize klass from o (location) and hash (options to created instance). # The object o is used to compute a source location. It may be nil. Source position is merged into # the given options (non surgically). If o is non-nil, the first found source position going up # the containment hierarchy is set. I.e. callers should pass nil if a source position is not wanted # or known to be unobtainable for the object. # # @param o [Object, nil] object from which source position / location is obtained, may be nil # @param klass [Class<Puppet::Parser::AST>] the ast class to create an instance of # @param hash [Hash] hash with options for the class to create # def ast(o, klass, hash = {}) # create and pass hash with file and line information # PUP-3274 - still needed since hostname transformation requires AST::HostName, and AST::Regexp klass.new(**merge_location(hash, o)) end # THIS IS AN EXPENSIVE OPERATION # The 3x AST requires line, pos etc. to be recorded directly in the AST nodes and this information # must be computed. # (Newer implementation only computes the information that is actually needed; typically when raising an # exception). # def merge_location(hash, o) if o pos = {} locator = o.locator offset = o.is_a?(Model::Program) ? 0 : o.offset pos[:line] = locator.line_for_offset(offset) pos[:pos] = locator.pos_on_line(offset) pos[:file] = locator.file if nil_or_empty?(pos[:file]) && !nil_or_empty?(@source_file) pos[:file] = @source_file end hash = hash.merge(pos) end hash end # Transforms pops expressions into AST 3.1 statements/expressions def transform(o) @@transform_visitor.visit_this_0(self, o) rescue StandardError => e loc_data = {} merge_location(loc_data, o) raise Puppet::ParseError.new(_("Error while transforming to Puppet 3 AST: %{message}") % { message: e.message }, loc_data[:file], loc_data[:line], loc_data[:pos], e) end # Transforms pops expressions into AST 3.1 query expressions def query(o) @@query_transform_visitor.visit_this_0(self, o) end # Transforms pops expressions into AST 3.1 hostnames def hostname(o) @@hostname_transform_visitor.visit_this_0(self, o) end # Ensures transformation fails if a 3.1 non supported object is encountered in a query expression # def query_Object(o) raise _("Not a valid expression in a collection query: %{class_name}") % { class_name: o.class.name } end # Transforms Array of host matching expressions into a (Ruby) array of AST::HostName def hostname_Array(o) o.collect { |x| ast x, AST::HostName, :value => hostname(x) } end def hostname_LiteralValue(o) o.value end def hostname_QualifiedName(o) o.value end def hostname_LiteralNumber(o) transform(o) # Number to string with correct radix end def hostname_LiteralDefault(o) 'default' end def hostname_LiteralRegularExpression(o) ast o, AST::Regex, :value => o.value end def hostname_Object(o) raise _("Illegal expression - unacceptable as a node name") end def transform_Object(o) raise _("Unacceptable transform - found an Object without a rule: %{klass}") % { klass: o.class } end # Nil, nop # Bee bopp a luh-lah, a bop bop boom. # def is_nop?(o) o.nil? || o.is_a?(Model::Nop) end def nil_or_empty?(x) x.nil? || x == '' end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/model/pn_transformer.rb
lib/puppet/pops/model/pn_transformer.rb
# frozen_string_literal: true require_relative '../../../puppet/concurrent/thread_local_singleton' module Puppet::Pops module Model class PNTransformer extend Puppet::Concurrent::ThreadLocalSingleton def self.transform(ast) singleton.transform(ast) end def initialize @visitor = Visitor.new(nil, 'transform', 0, 0) end def transform(ast) @visitor.visit_this_0(self, ast) end def transform_AccessExpression(e) PN::List.new([transform(e.left_expr)] + pn_array(e.keys)).as_call('access') end def transform_AndExpression(e) binary_op(e, 'and') end def transform_ArithmeticExpression(e) binary_op(e, e.operator) end def transform_Array(a) PN::List.new(pn_array(a)) end def transform_AssignmentExpression(e) binary_op(e, e.operator) end def transform_AttributeOperation(e) PN::Call.new(e.operator, PN::Literal.new(e.attribute_name), transform(e.value_expr)) end def transform_AttributesOperation(e) PN::Call.new('splat-hash', transform(e.expr)) end def transform_BlockExpression(e) transform(e.statements).as_call('block') end def transform_CallFunctionExpression(e) call_to_pn(e, 'call-lambda', 'invoke-lambda') end def transform_CallMethodExpression(e) call_to_pn(e, 'call-method', 'invoke-method') end def transform_CallNamedFunctionExpression(e) call_to_pn(e, 'call', 'invoke') end def transform_CaseExpression(e) PN::Call.new('case', transform(e.test), transform(e.options)) end def transform_CaseOption(e) PN::Map.new([transform(e.values).with_name('when'), block_as_entry('then', e.then_expr)]) end def transform_CollectExpression(e) entries = [transform(e.type_expr).with_name('type'), transform(e.query).with_name('query')] entries << transform(e.operations).with_name('ops') unless e.operations.empty? PN::Map.new(entries).as_call('collect') end def transform_ComparisonExpression(e) binary_op(e, e.operator) end def transform_ConcatenatedString(e) transform(e.segments).as_call('concat') end def transform_EppExpression(e) e.body.nil? ? PN::Call.new('epp') : transform(e.body).as_call('epp') end def transform_ExportedQuery(e) is_nop?(e.expr) ? PN::Call.new('exported-query') : PN::Call.new('exported-query', transform(e.expr)) end def transform_Factory(e) transform(e.model) end def transform_FunctionDefinition(e) definition_to_pn(e, 'function', nil, e.return_type) end def transform_HeredocExpression(e) entries = [] entries << PN::Literal.new(e.syntax).with_name('syntax') unless e.syntax == '' entries << transform(e.text_expr).with_name('text') PN::Map.new(entries).as_call('heredoc') end def transform_HostClassDefinition(e) definition_to_pn(e, 'class', e.parent_class) end def transform_IfExpression(e) if_to_pn(e, 'if') end def transform_InExpression(e) binary_op(e, 'in') end def transform_KeyedEntry(e) PN::Call.new('=>', transform(e.key), transform(e.value)) end def transform_LambdaExpression(e) entries = [] entries << parameters_entry(e.parameters) unless e.parameters.empty? entries << transform(e.return_type).with_name('returns') unless e.return_type.nil? entries << block_as_entry('body', e.body) unless e.body.nil? PN::Map.new(entries).as_call('lambda') end def transform_LiteralBoolean(e) PN::Literal.new(e.value) end def transform_LiteralDefault(_) PN::Call.new('default') end def transform_LiteralFloat(e) PN::Literal.new(e.value) end def transform_LiteralHash(e) transform(e.entries).as_call('hash') end def transform_LiteralInteger(e) vl = PN::Literal.new(e.value) e.radix == 10 ? vl : PN::Map.new([PN::Literal.new(e.radix).with_name('radix'), vl.with_name('value')]).as_call('int') end def transform_LiteralList(e) transform(e.values).as_call('array') end def transform_LiteralRegularExpression(e) PN::Literal.new(Types::PRegexpType.regexp_to_s(e.value)).as_call('regexp') end def transform_LiteralString(e) PN::Literal.new(e.value) end def transform_LiteralUndef(_) PN::Literal.new(nil) end def transform_MatchExpression(e) binary_op(e, e.operator) end def transform_NamedAccessExpression(e) binary_op(e, '.') end def transform_NodeDefinition(e) entries = [transform(e.host_matches).with_name('matches')] entries << transform(e.parent).with_name('parent') unless e.parent.nil? entries << block_as_entry('body', e.body) unless e.body.nil? PN::Map.new(entries).as_call('node') end def transform_Nop(_) PN::Call.new('nop') end # Some elements may have a nil element instead of a Nop Expression def transform_NilClass(e) PN::Call.new('nop') end def transform_NotExpression(e) PN::Call.new('!', transform(e.expr)) end def transform_OrExpression(e) binary_op(e, 'or') end def transform_Parameter(e) entries = [PN::Literal.new(e.name).with_name('name')] entries << transform(e.type_expr).with_name('type') unless e.type_expr.nil? entries << PN::Literal.new(true).with_name('splat') if e.captures_rest entries << transform(e.value).with_name('value') unless e.value.nil? PN::Map.new(entries).with_name('param') end def transform_ParenthesizedExpression(e) PN::Call.new('paren', transform(e.expr)) end def transform_PlanDefinition(e) definition_to_pn(e, 'plan', nil, e.return_type) end def transform_Program(e) transform(e.body) end def transform_QualifiedName(e) PN::Call.new('qn', PN::Literal.new(e.value)) end def transform_QualifiedReference(e) PN::Call.new('qr', PN::Literal.new(e.cased_value)) end def transform_RelationshipExpression(e) binary_op(e, e.operator) end def transform_RenderExpression(e) PN::Call.new('render', transform(e.expr)) end def transform_RenderStringExpression(e) PN::Literal.new(e.value).as_call('render-s') end def transform_ReservedWord(e) PN::Literal.new(e.word).as_call('reserved') end def transform_ResourceBody(e) PN::Map.new([ transform(e.title).with_name('title'), transform(e.operations).with_name('ops') ]).as_call('resource_body') end def transform_ResourceDefaultsExpression(e) entries = [transform(e.type_ref).with_name('type'), transform(e.operations).with_name('ops')] entries << PN::Literal.new(e.form).with_name('form') unless e.form == 'regular' PN::Map.new(entries).as_call('resource-defaults') end def transform_ResourceExpression(e) entries = [ transform(e.type_name).with_name('type'), PN::List.new(pn_array(e.bodies).map { |body| body[0] }).with_name('bodies') ] entries << PN::Literal.new(e.form).with_name('form') unless e.form == 'regular' PN::Map.new(entries).as_call('resource') end def transform_ResourceOverrideExpression(e) entries = [transform(e.resources).with_name('resources'), transform(e.operations).with_name('ops')] entries << PN::Literal.new(e.form).with_name('form') unless e.form == 'regular' PN::Map.new(entries).as_call('resource-override') end def transform_ResourceTypeDefinition(e) definition_to_pn(e, 'define') end def transform_SelectorEntry(e) PN::Call.new('=>', transform(e.matching_expr), transform(e.value_expr)) end def transform_SelectorExpression(e) PN::Call.new('?', transform(e.left_expr), transform(e.selectors)) end def transform_TextExpression(e) PN::Call.new('str', transform(e.expr)) end def transform_TypeAlias(e) PN::Call.new('type-alias', PN::Literal.new(e.name), transform(e.type_expr)) end def transform_TypeDefinition(e) PN::Call.new('type-definition', PN::Literal.new(e.name), PN::Literal.new(e.parent), transform(e.body)) end def transform_TypeMapping(e) PN::Call.new('type-mapping', transform(e.type_expr), transform(e.mapping_expr)) end def transform_UnaryMinusExpression(e) if e.expr.is_a?(LiteralValue) v = e.expr.value if v.is_a?(Numeric) return PN::Literal.new(-v) end end PN::Call.new('-', transform(e.expr)) end def transform_UnfoldExpression(e) PN::Call.new('unfold', transform(e.expr)) end def transform_UnlessExpression(e) if_to_pn(e, 'unless') end def transform_VariableExpression(e) ne = e.expr PN::Call.new('var', ne.is_a?(Model::QualifiedName) ? PN::Literal.new(ne.value) : transform(ne)) end def transform_VirtualQuery(e) is_nop?(e.expr) ? PN::Call.new('virtual-query') : PN::Call.new('virtual-query', transform(e.expr)) end def is_nop?(e) e.nil? || e.is_a?(Nop) end def binary_op(e, op) PN::Call.new(op, transform(e.left_expr), transform(e.right_expr)) end def definition_to_pn(e, type_name, parent = nil, return_type = nil) entries = [PN::Literal.new(e.name).with_name('name')] entries << PN::Literal.new(parent).with_name('parent') unless parent.nil? entries << parameters_entry(e.parameters) unless e.parameters.empty? entries << block_as_entry('body', e.body) unless e.body.nil? entries << transform(return_type).with_name('returns') unless return_type.nil? PN::Map.new(entries).as_call(type_name) end def parameters_entry(parameters) PN::Map.new(parameters.map do |p| entries = [] entries << transform(p.type_expr).with_name('type') unless p.type_expr.nil? entries << PN::Literal(true).with_name('splat') if p.captures_rest entries << transform(p.value).with_name('value') unless p.value.nil? PN::Map.new(entries).with_name(p.name) end).with_name('params') end def block_as_entry(name, expr) if expr.is_a?(BlockExpression) transform(expr.statements).with_name(name) else transform([expr]).with_name(name) end end def pn_array(a) a.map { |e| transform(e) } end def call_to_pn(e, r, nr) entries = [transform(e.functor_expr).with_name('functor'), transform(e.arguments).with_name('args')] entries << transform(e.lambda).with_name('block') unless e.lambda.nil? PN::Map.new(entries).as_call(e.rval_required ? r : nr) end def if_to_pn(e, name) entries = [transform(e.test).with_name('test')] entries << block_as_entry('then', e.then_expr) unless is_nop?(e.then_expr) entries << block_as_entry('else', e.else_expr) unless is_nop?(e.else_expr) PN::Map.new(entries).as_call(name) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/model/factory.rb
lib/puppet/pops/model/factory.rb
# frozen_string_literal: true # Factory is a helper class that makes construction of a Pops Model # much more convenient. It can be viewed as a small internal DSL for model # constructions. # For usage see tests using the factory. # # @todo All those uppercase methods ... they look bad in one way, but stand out nicely in the grammar... # decide if they should change into lower case names (some of the are lower case)... # module Puppet::Pops module Model class Factory # Shared build_visitor, since there are many instances of Factory being used KEY_LENGTH = 'length' KEY_OFFSET = 'offset' KEY_LOCATOR = 'locator' KEY_OPERATOR = 'operator' KEY_VALUE = 'value' KEY_KEYS = 'keys' KEY_NAME = 'name' KEY_BODY = 'body' KEY_EXPR = 'expr' KEY_LEFT_EXPR = 'left_expr' KEY_RIGHT_EXPR = 'right_expr' KEY_PARAMETERS = 'parameters' BUILD_VISITOR = Visitor.new(self, 'build') INFER_VISITOR = Visitor.new(self, 'infer') INTERPOLATION_VISITOR = Visitor.new(self, 'interpolate') MAPOFFSET_VISITOR = Visitor.new(self, 'map_offset') def self.infer(o) if o.instance_of?(Factory) o else new(o) end end attr_reader :model_class, :unfolded def [](key) @init_hash[key] end def []=(key, value) @init_hash[key] = value end def all_factories(&block) block.call(self) @init_hash.each_value { |value| value.all_factories(&block) if value.instance_of?(Factory) } end def model if @current.nil? # Assign a default Locator if it's missing. Should only happen when the factory is used by other # means than from a parser (e.g. unit tests) unless @init_hash.include?(KEY_LOCATOR) @init_hash[KEY_LOCATOR] = Parser::Locator.locator('<no source>', 'no file') unless @model_class <= Program @init_hash[KEY_OFFSET] = 0 @init_hash[KEY_LENGTH] = 0 end end @current = create_model end @current end # Backward API compatibility alias current model def create_model @init_hash.each_pair { |key, elem| @init_hash[key] = factory_to_model(elem) } model_class.from_asserted_hash(@init_hash) end # Initialize a factory with a single object, or a class with arguments applied to build of # created instance # def initialize(o, *args) @init_hash = {} if o.instance_of?(Class) @model_class = o BUILD_VISITOR.visit_this_class(self, o, args) else INFER_VISITOR.visit_this(self, o, EMPTY_ARRAY) end end def map_offset(model, locator) MAPOFFSET_VISITOR.visit_this_1(self, model, locator) end def map_offset_Object(o, locator) o end def map_offset_Factory(o, locator) map_offset(o.model, locator) end def map_offset_Positioned(o, locator) # Transpose the local offset, length to global "coordinates" global_offset, global_length = locator.to_global(o.offset, o.length) # mutate o.instance_variable_set(:'@offset', global_offset) o.instance_variable_set(:'@length', global_length) # Change locator since the positions were transposed to the global coordinates o.instance_variable_set(:'@locator', locator.locator) if locator.is_a? Puppet::Pops::Parser::Locator::SubLocator end # Polymorphic interpolate def interpolate INTERPOLATION_VISITOR.visit_this_class(self, @model_class, EMPTY_ARRAY) end # Building of Model classes def build_ArithmeticExpression(o, op, a, b) @init_hash[KEY_OPERATOR] = op build_BinaryExpression(o, a, b) end def build_AssignmentExpression(o, op, a, b) @init_hash[KEY_OPERATOR] = op build_BinaryExpression(o, a, b) end def build_AttributeOperation(o, name, op, value) @init_hash[KEY_OPERATOR] = op @init_hash['attribute_name'] = name.to_s # BOOLEAN is allowed in the grammar @init_hash['value_expr'] = value end def build_AttributesOperation(o, value) @init_hash[KEY_EXPR] = value end def build_AccessExpression(o, left, keys) @init_hash[KEY_LEFT_EXPR] = left @init_hash[KEY_KEYS] = keys end def build_BinaryExpression(o, left, right) @init_hash[KEY_LEFT_EXPR] = left @init_hash[KEY_RIGHT_EXPR] = right end def build_BlockExpression(o, args) @init_hash['statements'] = args end def build_EppExpression(o, parameters_specified, body) @init_hash['parameters_specified'] = parameters_specified b = f_build_body(body) @init_hash[KEY_BODY] = b unless b.nil? end # @param rval_required [Boolean] if the call must produce a value def build_CallExpression(o, functor, rval_required, args) @init_hash['functor_expr'] = functor @init_hash['rval_required'] = rval_required @init_hash['arguments'] = args end def build_CallMethodExpression(o, functor, rval_required, lambda, args) build_CallExpression(o, functor, rval_required, args) @init_hash['lambda'] = lambda end def build_CaseExpression(o, test, args) @init_hash['test'] = test @init_hash['options'] = args end def build_CaseOption(o, value_list, then_expr) value_list = [value_list] unless value_list.is_a?(Array) @init_hash['values'] = value_list b = f_build_body(then_expr) @init_hash['then_expr'] = b unless b.nil? end def build_CollectExpression(o, type_expr, query_expr, attribute_operations) @init_hash['type_expr'] = type_expr @init_hash['query'] = query_expr @init_hash['operations'] = attribute_operations end def build_ComparisonExpression(o, op, a, b) @init_hash[KEY_OPERATOR] = op build_BinaryExpression(o, a, b) end def build_ConcatenatedString(o, args) # Strip empty segments @init_hash['segments'] = args.reject { |arg| arg.model_class == LiteralString && arg['value'].empty? } end def build_HeredocExpression(o, name, expr) @init_hash['syntax'] = name @init_hash['text_expr'] = expr end # @param name [String] a valid classname # @param parameters [Array<Parameter>] may be empty # @param parent_class_name [String, nil] a valid classname referencing a parent class, optional. # @param body [Array<Expression>, Expression, nil] expression that constitute the body # @return [HostClassDefinition] configured from the parameters # def build_HostClassDefinition(o, name, parameters, parent_class_name, body) build_NamedDefinition(o, name, parameters, body) @init_hash['parent_class'] = parent_class_name unless parent_class_name.nil? end def build_ResourceOverrideExpression(o, resources, attribute_operations) @init_hash['resources'] = resources @init_hash['operations'] = attribute_operations end def build_ReservedWord(o, name, future) @init_hash['word'] = name @init_hash['future'] = future end def build_KeyedEntry(o, k, v) @init_hash['key'] = k @init_hash[KEY_VALUE] = v end def build_LiteralHash(o, keyed_entries, unfolded) @init_hash['entries'] = keyed_entries @unfolded = unfolded end def build_LiteralList(o, values) @init_hash['values'] = values end def build_LiteralFloat(o, val) @init_hash[KEY_VALUE] = val end def build_LiteralInteger(o, val, radix) @init_hash[KEY_VALUE] = val @init_hash['radix'] = radix end def build_LiteralString(o, value) @init_hash[KEY_VALUE] = val end def build_IfExpression(o, t, ift, els) @init_hash['test'] = t @init_hash['then_expr'] = ift @init_hash['else_expr'] = els end def build_ApplyExpression(o, args, body) @init_hash['arguments'] = args @init_hash['body'] = body end def build_MatchExpression(o, op, a, b) @init_hash[KEY_OPERATOR] = op build_BinaryExpression(o, a, b) end # Building model equivalences of Ruby objects # Allows passing regular ruby objects to the factory to produce instructions # that when evaluated produce the same thing. def infer_String(o) @model_class = LiteralString @init_hash[KEY_VALUE] = o end def infer_NilClass(o) @model_class = Nop end def infer_TrueClass(o) @model_class = LiteralBoolean @init_hash[KEY_VALUE] = o end def infer_FalseClass(o) @model_class = LiteralBoolean @init_hash[KEY_VALUE] = o end def infer_Integer(o) @model_class = LiteralInteger @init_hash[KEY_VALUE] = o end def infer_Float(o) @model_class = LiteralFloat @init_hash[KEY_VALUE] = o end def infer_Regexp(o) @model_class = LiteralRegularExpression @init_hash['pattern'] = o.inspect @init_hash[KEY_VALUE] = o end # Creates a String literal, unless the symbol is one of the special :undef, or :default # which instead creates a LiterlUndef, or a LiteralDefault. # Supports :undef because nil creates a no-op instruction. def infer_Symbol(o) case o when :undef @model_class = LiteralUndef when :default @model_class = LiteralDefault else infer_String(o.to_s) end end # Creates a LiteralList instruction from an Array, where the entries are built. def infer_Array(o) @model_class = LiteralList @init_hash['values'] = o.map { |e| Factory.infer(e) } end # Create a LiteralHash instruction from a hash, where keys and values are built # The hash entries are added in sorted order based on key.to_s # def infer_Hash(o) @model_class = LiteralHash @init_hash['entries'] = o.sort_by { |k, _| k.to_s }.map { |k, v| Factory.new(KeyedEntry, Factory.infer(k), Factory.infer(v)) } @unfolded = false end def f_build_body(body) case body when NilClass nil when Array Factory.new(BlockExpression, body) when Factory body else Factory.infer(body) end end def build_LambdaExpression(o, parameters, body, return_type) @init_hash[KEY_PARAMETERS] = parameters b = f_build_body(body) @init_hash[KEY_BODY] = b unless b.nil? @init_hash['return_type'] = return_type unless return_type.nil? end def build_NamedDefinition(o, name, parameters, body) @init_hash[KEY_PARAMETERS] = parameters b = f_build_body(body) @init_hash[KEY_BODY] = b unless b.nil? @init_hash[KEY_NAME] = name end def build_FunctionDefinition(o, name, parameters, body, return_type) @init_hash[KEY_PARAMETERS] = parameters b = f_build_body(body) @init_hash[KEY_BODY] = b unless b.nil? @init_hash[KEY_NAME] = name @init_hash['return_type'] = return_type unless return_type.nil? end def build_PlanDefinition(o, name, parameters, body, return_type = nil) @init_hash[KEY_PARAMETERS] = parameters b = f_build_body(body) @init_hash[KEY_BODY] = b unless b.nil? @init_hash[KEY_NAME] = name @init_hash['return_type'] = return_type unless return_type.nil? end def build_NodeDefinition(o, hosts, parent, body) @init_hash['host_matches'] = hosts @init_hash['parent'] = parent unless parent.nil? # no nop here b = f_build_body(body) @init_hash[KEY_BODY] = b unless b.nil? end def build_Parameter(o, name, expr) @init_hash[KEY_NAME] = name @init_hash[KEY_VALUE] = expr end def build_QualifiedReference(o, name) @init_hash['cased_value'] = name.to_s end def build_RelationshipExpression(o, op, a, b) @init_hash[KEY_OPERATOR] = op build_BinaryExpression(o, a, b) end def build_ResourceExpression(o, type_name, bodies) @init_hash['type_name'] = type_name @init_hash['bodies'] = bodies end def build_RenderStringExpression(o, string) @init_hash[KEY_VALUE] = string; end def build_ResourceBody(o, title_expression, attribute_operations) @init_hash['title'] = title_expression @init_hash['operations'] = attribute_operations end def build_ResourceDefaultsExpression(o, type_ref, attribute_operations) @init_hash['type_ref'] = type_ref @init_hash['operations'] = attribute_operations end def build_SelectorExpression(o, left, *selectors) @init_hash[KEY_LEFT_EXPR] = left @init_hash['selectors'] = selectors end def build_SelectorEntry(o, matching, value) @init_hash['matching_expr'] = matching @init_hash['value_expr'] = value end def build_QueryExpression(o, expr) @init_hash[KEY_EXPR] = expr unless Factory.nop?(expr) end def build_TypeAlias(o, name, type_expr) if type_expr.model_class <= KeyedEntry # KeyedEntry is used for the form: # # type Foo = Bar { ... } # # The entry contains Bar => { ... } and must be transformed into: # # Object[{parent => Bar, ... }] # parent = type_expr['key'] hash = type_expr['value'] pn = parent['cased_value'] unless pn == 'Object' || pn == 'TypeSet' hash['entries'] << Factory.KEY_ENTRY(Factory.QNAME('parent'), parent) parent = Factory.QREF('Object') end type_expr = parent.access([hash]) elsif type_expr.model_class <= LiteralHash # LiteralHash is used for the form: # # type Foo = { ... } # # The hash must be transformed into: # # Object[{ ... }] # type_expr = Factory.QREF('Object').access([type_expr]) end @init_hash['type_expr'] = type_expr @init_hash[KEY_NAME] = name end def build_TypeMapping(o, lhs, rhs) @init_hash['type_expr'] = lhs @init_hash['mapping_expr'] = rhs end def build_TypeDefinition(o, name, parent, body) b = f_build_body(body) @init_hash[KEY_BODY] = b unless b.nil? @init_hash['parent'] = parent @init_hash[KEY_NAME] = name end def build_UnaryExpression(o, expr) @init_hash[KEY_EXPR] = expr unless Factory.nop?(expr) end def build_Program(o, body, definitions, locator) @init_hash[KEY_BODY] = body # non containment @init_hash['definitions'] = definitions @init_hash[KEY_LOCATOR] = locator end def build_QualifiedName(o, name) @init_hash[KEY_VALUE] = name end def build_TokenValue(o) raise "Factory can not deal with a Lexer Token. Got token: #{o}. Probably caused by wrong index in grammar val[n]." end # Factory helpers def f_build_unary(klazz, expr) Factory.new(klazz, expr) end def f_build_binary_op(klazz, op, left, right) Factory.new(klazz, op, left, right) end def f_build_binary(klazz, left, right) Factory.new(klazz, left, right) end def f_arithmetic(op, r) f_build_binary_op(ArithmeticExpression, op, self, r) end def f_comparison(op, r) f_build_binary_op(ComparisonExpression, op, self, r) end def f_match(op, r) f_build_binary_op(MatchExpression, op, self, r) end # Operator helpers def in(r) f_build_binary(InExpression, self, r); end def or(r) f_build_binary(OrExpression, self, r); end def and(r) f_build_binary(AndExpression, self, r); end def not(); f_build_unary(NotExpression, self); end def minus(); f_build_unary(UnaryMinusExpression, self); end def unfold(); f_build_unary(UnfoldExpression, self); end def text(); f_build_unary(TextExpression, self); end def var(); f_build_unary(VariableExpression, self); end def access(r); f_build_binary(AccessExpression, self, r); end def dot r; f_build_binary(NamedAccessExpression, self, r); end def + r; f_arithmetic('+', r); end def - r; f_arithmetic('-', r); end def / r; f_arithmetic('/', r); end def * r; f_arithmetic('*', r); end def % r; f_arithmetic('%', r); end def << r; f_arithmetic('<<', r); end def >> r; f_arithmetic('>>', r); end def < r; f_comparison('<', r); end def <= r; f_comparison('<=', r); end def > r; f_comparison('>', r); end def >= r; f_comparison('>=', r); end def eq r; f_comparison('==', r); end def ne r; f_comparison('!=', r); end def =~ r; f_match('=~', r); end def mne r; f_match('!~', r); end def paren; f_build_unary(ParenthesizedExpression, self); end def relop(op, r) f_build_binary_op(RelationshipExpression, op, self, r) end def select(*args) Factory.new(SelectorExpression, self, *args) end # Same as access, but with varargs and arguments that must be inferred. For testing purposes def access_at(*r) f_build_binary(AccessExpression, self, r.map { |arg| Factory.infer(arg) }) end # For CaseExpression, setting the default for an already build CaseExpression def default(r) @init_hash['options'] << Factory.WHEN(Factory.infer(:default), r) self end def lambda=(lambda) @init_hash['lambda'] = lambda end # Assignment = def set(r) f_build_binary_op(AssignmentExpression, '=', self, r) end # Assignment += def plus_set(r) f_build_binary_op(AssignmentExpression, '+=', self, r) end # Assignment -= def minus_set(r) f_build_binary_op(AssignmentExpression, '-=', self, r) end def attributes(*args) @init_hash['attributes'] = args self end def offset @init_hash[KEY_OFFSET] end def length @init_hash[KEY_LENGTH] end # Records the position (start -> end) and computes the resulting length. # def record_position(locator, start_locatable, end_locatable) # record information directly in the Positioned object start_offset = start_locatable.offset @init_hash[KEY_LOCATOR] = locator @init_hash[KEY_OFFSET] = start_offset @init_hash[KEY_LENGTH] = end_locatable.nil? ? start_locatable.length : end_locatable.offset + end_locatable.length - start_offset self end # Sets the form of the resource expression (:regular (the default), :virtual, or :exported). # Produces true if the expression was a resource expression, false otherwise. # def self.set_resource_form(expr, form) # Note: Validation handles illegal combinations return false unless expr.instance_of?(self) && expr.model_class <= AbstractResource expr['form'] = form true end # Returns symbolic information about an expected shape of a resource expression given the LHS of a resource expr. # # * `name { }` => `:resource`, create a resource of the given type # * `Name { }` => ':defaults`, set defaults for the referenced type # * `Name[] { }` => `:override`, overrides instances referenced by LHS # * _any other_ => ':error', all other are considered illegal # def self.resource_shape(expr) if expr == 'class' :class elsif expr.instance_of?(self) mc = expr.model_class if mc <= QualifiedName :resource elsif mc <= QualifiedReference :defaults elsif mc <= AccessExpression # if Resource[e], then it is not resource specific lhs = expr[KEY_LEFT_EXPR] if lhs.model_class <= QualifiedReference && lhs[KEY_VALUE] == 'resource' && expr[KEY_KEYS].size == 1 :defaults else :override end else :error end else :error end end # Factory starting points def self.literal(o); infer(o); end def self.minus(o); infer(o).minus; end def self.unfold(o); infer(o).unfold; end def self.var(o); infer(o).var; end def self.block(*args); new(BlockExpression, args.map { |arg| infer(arg) }); end def self.string(*args); new(ConcatenatedString, args.map { |arg| infer(arg) }); end def self.text(o); infer(o).text; end def self.IF(test_e, then_e, else_e); new(IfExpression, test_e, then_e, else_e); end def self.UNLESS(test_e, then_e, else_e); new(UnlessExpression, test_e, then_e, else_e); end def self.CASE(test_e, *options); new(CaseExpression, test_e, options); end def self.WHEN(values_list, block); new(CaseOption, values_list, block); end def self.MAP(match, value); new(SelectorEntry, match, value); end def self.KEY_ENTRY(key, val); new(KeyedEntry, key, val); end def self.HASH(entries); new(LiteralHash, entries, false); end def self.HASH_UNFOLDED(entries); new(LiteralHash, entries, true); end def self.HEREDOC(name, expr); new(HeredocExpression, name, expr); end def self.STRING(*args); new(ConcatenatedString, args); end def self.LIST(entries); new(LiteralList, entries); end def self.PARAM(name, expr = nil); new(Parameter, name, expr); end def self.NODE(hosts, parent, body); new(NodeDefinition, hosts, parent, body); end # Parameters # Mark parameter as capturing the rest of arguments def captures_rest @init_hash['captures_rest'] = true end # Set Expression that should evaluate to the parameter's type def type_expr(o) @init_hash['type_expr'] = o end # Creates a QualifiedName representation of o, unless o already represents a QualifiedName in which # case it is returned. # def self.fqn(o) o.instance_of?(Factory) && o.model_class <= QualifiedName ? self : new(QualifiedName, o) end # Creates a QualifiedName representation of o, unless o already represents a QualifiedName in which # case it is returned. # def self.fqr(o) o.instance_of?(Factory) && o.model_class <= QualifiedReference ? self : new(QualifiedReference, o) end def self.SUBLOCATE(token, expr_factory) # expr is a Factory wrapped LiteralString, or ConcatenatedString # The token is SUBLOCATED token which has a SubLocator as the token's locator # Use the SubLocator to recalculate the offsets and lengths. model = expr_factory.model locator = token.locator expr_factory.map_offset(model, locator) model._pcore_all_contents([]) { |element| expr_factory.map_offset(element, locator) } # Returned the factory wrapping the now offset/length transformed expression(s) expr_factory end def self.TEXT(expr) new(TextExpression, infer(expr).interpolate) end # TODO_EPP def self.RENDER_STRING(o) new(RenderStringExpression, o) end def self.RENDER_EXPR(expr) new(RenderExpression, expr) end def self.EPP(parameters, body) if parameters.nil? params = [] parameters_specified = false else params = parameters parameters_specified = true end LAMBDA(params, new(EppExpression, parameters_specified, body), nil) end def self.RESERVED(name, future = false) new(ReservedWord, name, future) end # TODO: This is the same a fqn factory method, don't know if callers to fqn and QNAME can live with the # same result or not yet - refactor into one method when decided. # def self.QNAME(name) new(QualifiedName, name) end def self.NUMBER(name_or_numeric) n_radix = Utils.to_n_with_radix(name_or_numeric) if n_radix val, radix = n_radix if val.is_a?(Float) new(LiteralFloat, val) else new(LiteralInteger, val, radix) end else # Bad number should already have been caught by lexer - this should never happen # TRANSLATORS 'NUMBER' refers to a method name and the 'name_or_numeric' was the passed in value and should not be translated raise ArgumentError, _("Internal Error, NUMBER token does not contain a valid number, %{name_or_numeric}") % { name_or_numeric: name_or_numeric } end end # Convert input string to either a qualified name, a LiteralInteger with radix, or a LiteralFloat # def self.QNAME_OR_NUMBER(name) n_radix = Utils.to_n_with_radix(name) if n_radix val, radix = n_radix if val.is_a?(Float) new(LiteralFloat, val) else new(LiteralInteger, val, radix) end else new(QualifiedName, name) end end def self.QREF(name) new(QualifiedReference, name) end def self.VIRTUAL_QUERY(query_expr) new(VirtualQuery, query_expr) end def self.EXPORTED_QUERY(query_expr) new(ExportedQuery, query_expr) end def self.ARGUMENTS(args, arg) if !args.empty? && arg.model_class <= LiteralHash && arg.unfolded last = args[args.size() - 1] if last.model_class <= LiteralHash && last.unfolded last['entries'].concat(arg['entries']) return args end end args.push(arg) end def self.ATTRIBUTE_OP(name, op, expr) new(AttributeOperation, name, op, expr) end def self.ATTRIBUTES_OP(expr) new(AttributesOperation, expr) end # Same as CALL_NAMED but with inference and varargs (for testing purposes) def self.call_named(name, rval_required, *argument_list) new(CallNamedFunctionExpression, fqn(name), rval_required, argument_list.map { |arg| infer(arg) }) end def self.CALL_NAMED(name, rval_required, argument_list) new(CallNamedFunctionExpression, name, rval_required, argument_list) end def self.CALL_METHOD(functor, argument_list) new(CallMethodExpression, functor, true, nil, argument_list) end def self.COLLECT(type_expr, query_expr, attribute_operations) new(CollectExpression, type_expr, query_expr, attribute_operations) end def self.NAMED_ACCESS(type_name, bodies) new(NamedAccessExpression, type_name, bodies) end def self.RESOURCE(type_name, bodies) new(ResourceExpression, type_name, bodies) end def self.RESOURCE_DEFAULTS(type_name, attribute_operations) new(ResourceDefaultsExpression, type_name, attribute_operations) end def self.RESOURCE_OVERRIDE(resource_ref, attribute_operations) new(ResourceOverrideExpression, resource_ref, attribute_operations) end def self.RESOURCE_BODY(resource_title, attribute_operations) new(ResourceBody, resource_title, attribute_operations) end def self.PROGRAM(body, definitions, locator) new(Program, body, definitions, locator) end # Builds a BlockExpression if args size > 1, else the single expression/value in args def self.block_or_expression(args, left_brace = nil, right_brace = nil) if args.size > 1 block_expr = new(BlockExpression, args) # If given a left and right brace position, use those # otherwise use the first and last element of the block if !left_brace.nil? && !right_brace.nil? block_expr.record_position(args.first[KEY_LOCATOR], left_brace, right_brace) else block_expr.record_position(args.first[KEY_LOCATOR], args.first, args.last) end block_expr else args[0] end end def self.HOSTCLASS(name, parameters, parent, body) new(HostClassDefinition, name, parameters, parent, body) end def self.DEFINITION(name, parameters, body) new(ResourceTypeDefinition, name, parameters, body) end def self.PLAN(name, parameters, body) new(PlanDefinition, name, parameters, body, nil) end def self.APPLY(arguments, body) new(ApplyExpression, arguments, body) end def self.APPLY_BLOCK(statements) new(ApplyBlockExpression, statements) end def self.FUNCTION(name, parameters, body, return_type) new(FunctionDefinition, name, parameters, body, return_type) end def self.LAMBDA(parameters, body, return_type) new(LambdaExpression, parameters, body, return_type) end def self.TYPE_ASSIGNMENT(lhs, rhs) if lhs.model_class <= AccessExpression new(TypeMapping, lhs, rhs) else new(TypeAlias, lhs['cased_value'], rhs) end end def self.TYPE_DEFINITION(name, parent, body) new(TypeDefinition, name, parent, body) end def self.nop? o o.nil? || o.instance_of?(Factory) && o.model_class <= Nop end STATEMENT_CALLS = { 'require' => true, 'realize' => true, 'include' => true, 'contain' => true, 'tag' => true, 'debug' => true, 'info' => true, 'notice' => true, 'warning' => true, 'err' => true, 'fail' => true, 'import' => true, # discontinued, but transform it to make it call error reporting function 'break' => true, 'next' => true, 'return' => true }.freeze # Returns true if the given name is a "statement keyword" (require, include, contain, # error, notice, info, debug # def self.name_is_statement?(name) STATEMENT_CALLS.include?(name) end class ArgsToNonCallError < RuntimeError attr_reader :args, :name_expr def initialize(args, name_expr) @args = args @name_expr = name_expr end end # Transforms an array of expressions containing literal name expressions to calls if followed by an # expression, or expression list. # def self.transform_calls(expressions) expressions.each_with_object([]) do |expr, memo| name = memo[-1] if name.instance_of?(Factory) && name.model_class <= QualifiedName && name_is_statement?(name[KEY_VALUE]) if expr.is_a?(Array) expr = expr.reject { |e| e.is_a?(Parser::LexerSupport::TokenValue) } else expr = [expr] end the_call = self.CALL_NAMED(name, false, expr) # last positioned is last arg if there are several the_call.record_position(name[KEY_LOCATOR], name, expr[-1]) memo[-1] = the_call if expr.is_a?(CallNamedFunctionExpression) # Patch statement function call to expression style # This is needed because it is first parsed as a "statement" and the requirement changes as it becomes # an argument to the name to call transform above. expr.rval_required = true end elsif expr.is_a?(Array) raise ArgsToNonCallError.new(expr, name) else memo << expr if expr.model_class <= CallNamedFunctionExpression # Patch rvalue expression function call to statement style. # This is not really required but done to be AST model compliant expr['rval_required'] = false end end end end # Transforms a left expression followed by an untitled resource (in the form of attribute_operations) # @param left [Factory, Expression] the lhs followed what may be a hash def self.transform_resource_wo_title(left, attribute_ops, lbrace_token, rbrace_token) # Returning nil means accepting the given as a potential resource expression return nil unless attribute_ops.is_a? Array return nil unless left.model_class <= QualifiedName keyed_entries = attribute_ops.map do |ao| return nil if ao[KEY_OPERATOR] == '+>' KEY_ENTRY(infer(ao['attribute_name']), ao['value_expr']) end a_hash = HASH(keyed_entries) a_hash.record_position(left[KEY_LOCATOR], lbrace_token, rbrace_token) block_or_expression(transform_calls([left, a_hash])) end def interpolate_Factory(c) self end def interpolate_LiteralInteger(c) # convert number to a variable var end def interpolate_Object(c) self end def interpolate_QualifiedName(c) var end # rewrite left expression to variable if it is name, number, and recurse if it is an access expression # this is for interpolation support in new lexer (${NAME}, ${NAME[}}, ${NUMBER}, ${NUMBER[]} - all # other expressions requires variables to be preceded with $ # def interpolate_AccessExpression(c) lhs = @init_hash[KEY_LEFT_EXPR] if is_interop_rewriteable?(lhs) @init_hash[KEY_LEFT_EXPR] = lhs.interpolate end self end def interpolate_NamedAccessExpression(c) lhs = @init_hash[KEY_LEFT_EXPR] if is_interop_rewriteable?(lhs) @init_hash[KEY_LEFT_EXPR] = lhs.interpolate end self end # Rewrite method calls on the form ${x.each ...} to ${$x.each} def interpolate_CallMethodExpression(c) functor_expr = @init_hash['functor_expr'] if is_interop_rewriteable?(functor_expr) @init_hash['functor_expr'] = functor_expr.interpolate end self end def is_interop_rewriteable?(o) mc = o.model_class if mc <= AccessExpression || mc <= QualifiedName || mc <= NamedAccessExpression || mc <= CallMethodExpression true elsif mc <= LiteralInteger # Only decimal integers can represent variables, else it is a number o['radix'] == 10 else false end end def self.concat(*args) result = ''.dup
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/model/model_label_provider.rb
lib/puppet/pops/model/model_label_provider.rb
# frozen_string_literal: true module Puppet::Pops module Model # A provider of labels for model object, producing a human name for the model object. # As an example, if object is an ArithmeticExpression with operator +, `#a_an(o)` produces "a '+' Expression", # #the(o) produces "the + Expression", and #label produces "+ Expression". # class ModelLabelProvider include LabelProvider def initialize @@label_visitor ||= Visitor.new(self, "label", 0, 0) end # Produces a label for the given objects type/operator without article. # If a Class is given, its name is used as label # def label o @@label_visitor.visit_this_0(self, o) end # rubocop:disable Layout/SpaceBeforeSemicolon def label_Factory o ; label(o.model) end def label_Array o ; "Array" end def label_LiteralInteger o ; "Literal Integer" end def label_LiteralFloat o ; "Literal Float" end def label_ArithmeticExpression o ; "'#{o.operator}' expression" end def label_AccessExpression o ; "'[]' expression" end def label_MatchExpression o ; "'#{o.operator}' expression" end def label_CollectExpression o ; label(o.query) end def label_EppExpression o ; "Epp Template" end def label_ExportedQuery o ; "Exported Query" end def label_VirtualQuery o ; "Virtual Query" end def label_QueryExpression o ; "Collect Query" end def label_ComparisonExpression o ; "'#{o.operator}' expression" end def label_AndExpression o ; "'and' expression" end def label_OrExpression o ; "'or' expression" end def label_InExpression o ; "'in' expression" end def label_AssignmentExpression o ; "'#{o.operator}' expression" end def label_AttributeOperation o ; "'#{o.operator}' expression" end def label_LiteralList o ; "Array Expression" end def label_LiteralHash o ; "Hash Expression" end def label_KeyedEntry o ; "Hash Entry" end def label_LiteralBoolean o ; "Boolean" end def label_TrueClass o ; "Boolean" end def label_FalseClass o ; "Boolean" end def label_LiteralString o ; "String" end def label_LambdaExpression o ; "Lambda" end def label_LiteralDefault o ; "'default' expression" end def label_LiteralUndef o ; "'undef' expression" end def label_LiteralRegularExpression o ; "Regular Expression" end def label_Nop o ; "Nop Expression" end def label_NamedAccessExpression o ; "'.' expression" end def label_NilClass o ; "Undef Value" end def label_NotExpression o ; "'not' expression" end def label_VariableExpression o ; "Variable" end def label_TextExpression o ; "Expression in Interpolated String" end def label_UnaryMinusExpression o ; "Unary Minus" end def label_UnfoldExpression o ; "Unfold" end def label_BlockExpression o ; "Block Expression" end def label_ApplyBlockExpression o ; "Apply Block Expression" end def label_ConcatenatedString o ; "Double Quoted String" end def label_HeredocExpression o ; "'@(#{o.syntax})' expression" end def label_HostClassDefinition o ; "Host Class Definition" end def label_FunctionDefinition o ; "Function Definition" end def label_PlanDefinition o ; "Plan Definition" end def label_NodeDefinition o ; "Node Definition" end def label_ResourceTypeDefinition o ; "'define' expression" end def label_ResourceOverrideExpression o ; "Resource Override" end def label_Parameter o ; "Parameter Definition" end def label_ParenthesizedExpression o ; "Parenthesized Expression" end def label_IfExpression o ; "'if' statement" end def label_UnlessExpression o ; "'unless' Statement" end def label_CallNamedFunctionExpression o ; "Function Call" end def label_CallMethodExpression o ; "Method call" end def label_ApplyExpression o ; "'apply' expression" end def label_CaseExpression o ; "'case' statement" end def label_CaseOption o ; "Case Option" end def label_RenderStringExpression o ; "Epp Text" end def label_RenderExpression o ; "Epp Interpolated Expression" end def label_RelationshipExpression o ; "'#{o.operator}' expression" end def label_ResourceBody o ; "Resource Instance Definition" end def label_ResourceDefaultsExpression o ; "Resource Defaults Expression" end def label_ResourceExpression o ; "Resource Statement" end def label_SelectorExpression o ; "Selector Expression" end def label_SelectorEntry o ; "Selector Option" end def label_Integer o ; "Integer" end def label_Float o ; "Float" end def label_String o ; "String" end def label_Regexp o ; "Regexp" end def label_Object o ; "Object" end def label_Hash o ; "Hash" end def label_QualifiedName o ; "Name" end def label_QualifiedReference o ; "Type-Name" end def label_PAnyType o ; "#{o}-Type" end def label_ReservedWord o ; "Reserved Word '#{o.word}'" end def label_CatalogCollector o ; "Catalog-Collector" end def label_ExportedCollector o ; "Exported-Collector" end def label_TypeAlias o ; "Type Alias" end def label_TypeMapping o ; "Type Mapping" end def label_TypeDefinition o ; "Type Definition" end def label_Binary o ; "Binary" end def label_Sensitive o ; "Sensitive" end def label_Timestamp o ; "Timestamp" end def label_Timespan o ; "Timespan" end def label_Version o ; "Semver" end def label_VersionRange o ; "SemverRange" end # rubocop:enable Layout/SpaceBeforeSemicolon def label_PResourceType o if o.title "#{o} Resource-Reference" else "#{o}-Type" end end def label_Resource o 'Resource Statement' end def label_Class o if o <= Types::PAnyType simple_name = o.name.split('::').last simple_name[1..-5] + "-Type" else n = o.name if n.nil? n = o.respond_to?(:_pcore_type) ? o._pcore_type.name : 'Anonymous Class' end n end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/model/ast.rb
lib/puppet/pops/model/ast.rb
# frozen_string_literal: true # # Generated by Puppet::Pops::Types::RubyGenerator from TypeSet Puppet::AST on -4712-01-01 module Puppet module Pops module Model class PopsObject def self._pcore_type @_pcore_type ||= Types::PObjectType.new('Puppet::AST::PopsObject', { }) end include Types::PuppetObject def self.from_hash(init_hash) from_asserted_hash(Types::TypeAsserter.assert_instance_of('Puppet::AST::PopsObject initializer', _pcore_type.init_hash_type, init_hash)) end def self.from_asserted_hash(init_hash) new end def self.create new end attr_reader :hash def initialize @hash = 2270595461303489901 end def _pcore_init_hash {} end def _pcore_contents end def _pcore_all_contents(path) end def to_s Types::TypeFormatter.string(self) end def eql?(o) o.instance_of?(self.class) end alias == eql? end class Positioned < PopsObject def self._pcore_type @_pcore_type ||= Types::PObjectType .new('Puppet::AST::Positioned', { 'parent' => PopsObject._pcore_type, 'attributes' => { 'locator' => { 'type' => Parser::Locator::Locator19._pcore_type, 'kind' => 'reference' }, 'offset' => Types::PIntegerType::DEFAULT, 'length' => Types::PIntegerType::DEFAULT, 'file' => { 'type' => Types::PStringType::DEFAULT, 'kind' => 'derived' }, 'line' => { 'type' => Types::PIntegerType::DEFAULT, 'kind' => 'derived' }, 'pos' => { 'type' => Types::PIntegerType::DEFAULT, 'kind' => 'derived' } }, 'equality' => [] }) end def self.from_hash(init_hash) from_asserted_hash(Types::TypeAsserter.assert_instance_of('Puppet::AST::Positioned initializer', _pcore_type.init_hash_type, init_hash)) end def self.from_asserted_hash(init_hash) new( init_hash['locator'], init_hash['offset'], init_hash['length']) end def self.create(locator, offset, length) ta = Types::TypeAsserter attrs = _pcore_type.attributes(true) ta.assert_instance_of('Puppet::AST::Positioned[locator]', attrs['locator'].type, locator) ta.assert_instance_of('Puppet::AST::Positioned[offset]', attrs['offset'].type, offset) ta.assert_instance_of('Puppet::AST::Positioned[length]', attrs['length'].type, length) new(locator, offset, length) end attr_reader :locator attr_reader :offset attr_reader :length def file @locator.file end def line @locator.line_for_offset(@offset) end def pos @locator.pos_on_line(@offset) end def initialize(locator, offset, length) super() @locator = locator @offset = offset @length = length end def _pcore_init_hash result = super result['locator'] = @locator result['offset'] = @offset result['length'] = @length result end end class Expression < Positioned def self._pcore_type @_pcore_type ||= Types::PObjectType.new('Puppet::AST::Expression', { 'parent' => Positioned._pcore_type }) end end class Nop < Expression def self._pcore_type @_pcore_type ||= Types::PObjectType.new('Puppet::AST::Nop', { 'parent' => Expression._pcore_type }) end end class BinaryExpression < Expression def self._pcore_type @_pcore_type ||= Types::PObjectType.new('Puppet::AST::BinaryExpression', { 'parent' => Expression._pcore_type, 'attributes' => { 'left_expr' => Expression._pcore_type, 'right_expr' => Expression._pcore_type } }) end def self.from_hash(init_hash) from_asserted_hash(Types::TypeAsserter.assert_instance_of('Puppet::AST::BinaryExpression initializer', _pcore_type.init_hash_type, init_hash)) end def self.from_asserted_hash(init_hash) new( init_hash['locator'], init_hash['offset'], init_hash['length'], init_hash['left_expr'], init_hash['right_expr']) end def self.create(locator, offset, length, left_expr, right_expr) ta = Types::TypeAsserter attrs = _pcore_type.attributes(true) ta.assert_instance_of('Puppet::AST::Positioned[locator]', attrs['locator'].type, locator) ta.assert_instance_of('Puppet::AST::Positioned[offset]', attrs['offset'].type, offset) ta.assert_instance_of('Puppet::AST::Positioned[length]', attrs['length'].type, length) ta.assert_instance_of('Puppet::AST::BinaryExpression[left_expr]', attrs['left_expr'].type, left_expr) ta.assert_instance_of('Puppet::AST::BinaryExpression[right_expr]', attrs['right_expr'].type, right_expr) new(locator, offset, length, left_expr, right_expr) end attr_reader :left_expr attr_reader :right_expr def initialize(locator, offset, length, left_expr, right_expr) super(locator, offset, length) @hash = @hash ^ left_expr.hash ^ right_expr.hash @left_expr = left_expr @right_expr = right_expr end def _pcore_init_hash result = super result['left_expr'] = @left_expr result['right_expr'] = @right_expr result end def _pcore_contents yield(@left_expr) unless @left_expr.nil? yield(@right_expr) unless @right_expr.nil? end def _pcore_all_contents(path, &block) path << self unless @left_expr.nil? block.call(@left_expr, path) @left_expr._pcore_all_contents(path, &block) end unless @right_expr.nil? block.call(@right_expr, path) @right_expr._pcore_all_contents(path, &block) end path.pop end def eql?(o) super && @left_expr.eql?(o.left_expr) && @right_expr.eql?(o.right_expr) end alias == eql? end class UnaryExpression < Expression def self._pcore_type @_pcore_type ||= Types::PObjectType.new('Puppet::AST::UnaryExpression', { 'parent' => Expression._pcore_type, 'attributes' => { 'expr' => Expression._pcore_type } }) end def self.from_hash(init_hash) from_asserted_hash(Types::TypeAsserter.assert_instance_of('Puppet::AST::UnaryExpression initializer', _pcore_type.init_hash_type, init_hash)) end def self.from_asserted_hash(init_hash) new( init_hash['locator'], init_hash['offset'], init_hash['length'], init_hash['expr']) end def self.create(locator, offset, length, expr) ta = Types::TypeAsserter attrs = _pcore_type.attributes(true) ta.assert_instance_of('Puppet::AST::Positioned[locator]', attrs['locator'].type, locator) ta.assert_instance_of('Puppet::AST::Positioned[offset]', attrs['offset'].type, offset) ta.assert_instance_of('Puppet::AST::Positioned[length]', attrs['length'].type, length) ta.assert_instance_of('Puppet::AST::UnaryExpression[expr]', attrs['expr'].type, expr) new(locator, offset, length, expr) end attr_reader :expr def initialize(locator, offset, length, expr) super(locator, offset, length) @hash = @hash ^ expr.hash @expr = expr end def _pcore_init_hash result = super result['expr'] = @expr result end def _pcore_contents yield(@expr) unless @expr.nil? end def _pcore_all_contents(path, &block) path << self unless @expr.nil? block.call(@expr, path) @expr._pcore_all_contents(path, &block) end path.pop end def eql?(o) super && @expr.eql?(o.expr) end alias == eql? end class ParenthesizedExpression < UnaryExpression def self._pcore_type @_pcore_type ||= Types::PObjectType.new('Puppet::AST::ParenthesizedExpression', { 'parent' => UnaryExpression._pcore_type }) end def _pcore_contents yield(@expr) unless @expr.nil? end def _pcore_all_contents(path, &block) path << self unless @expr.nil? block.call(@expr, path) @expr._pcore_all_contents(path, &block) end path.pop end end class NotExpression < UnaryExpression def self._pcore_type @_pcore_type ||= Types::PObjectType.new('Puppet::AST::NotExpression', { 'parent' => UnaryExpression._pcore_type }) end def _pcore_contents yield(@expr) unless @expr.nil? end def _pcore_all_contents(path, &block) path << self unless @expr.nil? block.call(@expr, path) @expr._pcore_all_contents(path, &block) end path.pop end end class UnaryMinusExpression < UnaryExpression def self._pcore_type @_pcore_type ||= Types::PObjectType.new('Puppet::AST::UnaryMinusExpression', { 'parent' => UnaryExpression._pcore_type }) end def _pcore_contents yield(@expr) unless @expr.nil? end def _pcore_all_contents(path, &block) path << self unless @expr.nil? block.call(@expr, path) @expr._pcore_all_contents(path, &block) end path.pop end end class UnfoldExpression < UnaryExpression def self._pcore_type @_pcore_type ||= Types::PObjectType.new('Puppet::AST::UnfoldExpression', { 'parent' => UnaryExpression._pcore_type }) end def _pcore_contents yield(@expr) unless @expr.nil? end def _pcore_all_contents(path, &block) path << self unless @expr.nil? block.call(@expr, path) @expr._pcore_all_contents(path, &block) end path.pop end end class AssignmentExpression < BinaryExpression def self._pcore_type @_pcore_type ||= Types::PObjectType.new('Puppet::AST::AssignmentExpression', { 'parent' => BinaryExpression._pcore_type, 'attributes' => { 'operator' => Types::PEnumType.new(['+=', '-=', '=']) } }) end def self.from_hash(init_hash) from_asserted_hash(Types::TypeAsserter.assert_instance_of('Puppet::AST::AssignmentExpression initializer', _pcore_type.init_hash_type, init_hash)) end def self.from_asserted_hash(init_hash) new( init_hash['locator'], init_hash['offset'], init_hash['length'], init_hash['left_expr'], init_hash['right_expr'], init_hash['operator']) end def self.create(locator, offset, length, left_expr, right_expr, operator) ta = Types::TypeAsserter attrs = _pcore_type.attributes(true) ta.assert_instance_of('Puppet::AST::Positioned[locator]', attrs['locator'].type, locator) ta.assert_instance_of('Puppet::AST::Positioned[offset]', attrs['offset'].type, offset) ta.assert_instance_of('Puppet::AST::Positioned[length]', attrs['length'].type, length) ta.assert_instance_of('Puppet::AST::BinaryExpression[left_expr]', attrs['left_expr'].type, left_expr) ta.assert_instance_of('Puppet::AST::BinaryExpression[right_expr]', attrs['right_expr'].type, right_expr) ta.assert_instance_of('Puppet::AST::AssignmentExpression[operator]', attrs['operator'].type, operator) new(locator, offset, length, left_expr, right_expr, operator) end attr_reader :operator def initialize(locator, offset, length, left_expr, right_expr, operator) super(locator, offset, length, left_expr, right_expr) @hash = @hash ^ operator.hash @operator = operator end def _pcore_init_hash result = super result['operator'] = @operator result end def _pcore_contents yield(@left_expr) unless @left_expr.nil? yield(@right_expr) unless @right_expr.nil? end def _pcore_all_contents(path, &block) path << self unless @left_expr.nil? block.call(@left_expr, path) @left_expr._pcore_all_contents(path, &block) end unless @right_expr.nil? block.call(@right_expr, path) @right_expr._pcore_all_contents(path, &block) end path.pop end def eql?(o) super && @operator.eql?(o.operator) end alias == eql? end class ArithmeticExpression < BinaryExpression def self._pcore_type @_pcore_type ||= Types::PObjectType .new('Puppet::AST::ArithmeticExpression', { 'parent' => BinaryExpression._pcore_type, 'attributes' => { 'operator' => Types::PEnumType.new(['%', '*', '+', '-', '/', '<<', '>>']) } }) end def self.from_hash(init_hash) from_asserted_hash(Types::TypeAsserter.assert_instance_of('Puppet::AST::ArithmeticExpression initializer', _pcore_type.init_hash_type, init_hash)) end def self.from_asserted_hash(init_hash) new( init_hash['locator'], init_hash['offset'], init_hash['length'], init_hash['left_expr'], init_hash['right_expr'], init_hash['operator']) end def self.create(locator, offset, length, left_expr, right_expr, operator) ta = Types::TypeAsserter attrs = _pcore_type.attributes(true) ta.assert_instance_of('Puppet::AST::Positioned[locator]', attrs['locator'].type, locator) ta.assert_instance_of('Puppet::AST::Positioned[offset]', attrs['offset'].type, offset) ta.assert_instance_of('Puppet::AST::Positioned[length]', attrs['length'].type, length) ta.assert_instance_of('Puppet::AST::BinaryExpression[left_expr]', attrs['left_expr'].type, left_expr) ta.assert_instance_of('Puppet::AST::BinaryExpression[right_expr]', attrs['right_expr'].type, right_expr) ta.assert_instance_of('Puppet::AST::ArithmeticExpression[operator]', attrs['operator'].type, operator) new(locator, offset, length, left_expr, right_expr, operator) end attr_reader :operator def initialize(locator, offset, length, left_expr, right_expr, operator) super(locator, offset, length, left_expr, right_expr) @hash = @hash ^ operator.hash @operator = operator end def _pcore_init_hash result = super result['operator'] = @operator result end def _pcore_contents yield(@left_expr) unless @left_expr.nil? yield(@right_expr) unless @right_expr.nil? end def _pcore_all_contents(path, &block) path << self unless @left_expr.nil? block.call(@left_expr, path) @left_expr._pcore_all_contents(path, &block) end unless @right_expr.nil? block.call(@right_expr, path) @right_expr._pcore_all_contents(path, &block) end path.pop end def eql?(o) super && @operator.eql?(o.operator) end alias == eql? end class RelationshipExpression < BinaryExpression def self._pcore_type @_pcore_type ||= Types::PObjectType.new('Puppet::AST::RelationshipExpression', { 'parent' => BinaryExpression._pcore_type, 'attributes' => { 'operator' => Types::PEnumType.new(['->', '<-', '<~', '~>']) } }) end def self.from_hash(init_hash) from_asserted_hash(Types::TypeAsserter.assert_instance_of('Puppet::AST::RelationshipExpression initializer', _pcore_type.init_hash_type, init_hash)) end def self.from_asserted_hash(init_hash) new( init_hash['locator'], init_hash['offset'], init_hash['length'], init_hash['left_expr'], init_hash['right_expr'], init_hash['operator']) end def self.create(locator, offset, length, left_expr, right_expr, operator) ta = Types::TypeAsserter attrs = _pcore_type.attributes(true) ta.assert_instance_of('Puppet::AST::Positioned[locator]', attrs['locator'].type, locator) ta.assert_instance_of('Puppet::AST::Positioned[offset]', attrs['offset'].type, offset) ta.assert_instance_of('Puppet::AST::Positioned[length]', attrs['length'].type, length) ta.assert_instance_of('Puppet::AST::BinaryExpression[left_expr]', attrs['left_expr'].type, left_expr) ta.assert_instance_of('Puppet::AST::BinaryExpression[right_expr]', attrs['right_expr'].type, right_expr) ta.assert_instance_of('Puppet::AST::RelationshipExpression[operator]', attrs['operator'].type, operator) new(locator, offset, length, left_expr, right_expr, operator) end attr_reader :operator def initialize(locator, offset, length, left_expr, right_expr, operator) super(locator, offset, length, left_expr, right_expr) @hash = @hash ^ operator.hash @operator = operator end def _pcore_init_hash result = super result['operator'] = @operator result end def _pcore_contents yield(@left_expr) unless @left_expr.nil? yield(@right_expr) unless @right_expr.nil? end def _pcore_all_contents(path, &block) path << self unless @left_expr.nil? block.call(@left_expr, path) @left_expr._pcore_all_contents(path, &block) end unless @right_expr.nil? block.call(@right_expr, path) @right_expr._pcore_all_contents(path, &block) end path.pop end def eql?(o) super && @operator.eql?(o.operator) end alias == eql? end class AccessExpression < Expression def self._pcore_type @_pcore_type ||= Types::PObjectType .new('Puppet::AST::AccessExpression', { 'parent' => Expression._pcore_type, 'attributes' => { 'left_expr' => Expression._pcore_type, 'keys' => { 'type' => Types::PArrayType.new(Expression._pcore_type), 'value' => [] } } }) end def self.from_hash(init_hash) from_asserted_hash(Types::TypeAsserter.assert_instance_of('Puppet::AST::AccessExpression initializer', _pcore_type.init_hash_type, init_hash)) end def self.from_asserted_hash(init_hash) new( init_hash['locator'], init_hash['offset'], init_hash['length'], init_hash['left_expr'], init_hash.fetch('keys') { _pcore_type['keys'].value }) end def self.create(locator, offset, length, left_expr, keys = _pcore_type['keys'].value) ta = Types::TypeAsserter attrs = _pcore_type.attributes(true) ta.assert_instance_of('Puppet::AST::Positioned[locator]', attrs['locator'].type, locator) ta.assert_instance_of('Puppet::AST::Positioned[offset]', attrs['offset'].type, offset) ta.assert_instance_of('Puppet::AST::Positioned[length]', attrs['length'].type, length) ta.assert_instance_of('Puppet::AST::AccessExpression[left_expr]', attrs['left_expr'].type, left_expr) ta.assert_instance_of('Puppet::AST::AccessExpression[keys]', attrs['keys'].type, keys) new(locator, offset, length, left_expr, keys) end attr_reader :left_expr attr_reader :keys def initialize(locator, offset, length, left_expr, keys = _pcore_type['keys'].value) super(locator, offset, length) @hash = @hash ^ left_expr.hash ^ keys.hash @left_expr = left_expr @keys = keys end def _pcore_init_hash result = super result['left_expr'] = @left_expr result['keys'] = @keys unless _pcore_type['keys'].default_value?(@keys) result end def _pcore_contents yield(@left_expr) unless @left_expr.nil? @keys.each { |value| yield(value) } end def _pcore_all_contents(path, &block) path << self unless @left_expr.nil? block.call(@left_expr, path) @left_expr._pcore_all_contents(path, &block) end @keys.each do |value| block.call(value, path) value._pcore_all_contents(path, &block) end path.pop end def eql?(o) super && @left_expr.eql?(o.left_expr) && @keys.eql?(o.keys) end alias == eql? end class ComparisonExpression < BinaryExpression def self._pcore_type @_pcore_type ||= Types::PObjectType .new('Puppet::AST::ComparisonExpression', { 'parent' => BinaryExpression._pcore_type, 'attributes' => { 'operator' => Types::PEnumType.new(['!=', '<', '<=', '==', '>', '>=']) } }) end def self.from_hash(init_hash) from_asserted_hash(Types::TypeAsserter.assert_instance_of('Puppet::AST::ComparisonExpression initializer', _pcore_type.init_hash_type, init_hash)) end def self.from_asserted_hash(init_hash) new( init_hash['locator'], init_hash['offset'], init_hash['length'], init_hash['left_expr'], init_hash['right_expr'], init_hash['operator']) end def self.create(locator, offset, length, left_expr, right_expr, operator) ta = Types::TypeAsserter attrs = _pcore_type.attributes(true) ta.assert_instance_of('Puppet::AST::Positioned[locator]', attrs['locator'].type, locator) ta.assert_instance_of('Puppet::AST::Positioned[offset]', attrs['offset'].type, offset) ta.assert_instance_of('Puppet::AST::Positioned[length]', attrs['length'].type, length) ta.assert_instance_of('Puppet::AST::BinaryExpression[left_expr]', attrs['left_expr'].type, left_expr) ta.assert_instance_of('Puppet::AST::BinaryExpression[right_expr]', attrs['right_expr'].type, right_expr) ta.assert_instance_of('Puppet::AST::ComparisonExpression[operator]', attrs['operator'].type, operator) new(locator, offset, length, left_expr, right_expr, operator) end attr_reader :operator def initialize(locator, offset, length, left_expr, right_expr, operator) super(locator, offset, length, left_expr, right_expr) @hash = @hash ^ operator.hash @operator = operator end def _pcore_init_hash result = super result['operator'] = @operator result end def _pcore_contents yield(@left_expr) unless @left_expr.nil? yield(@right_expr) unless @right_expr.nil? end def _pcore_all_contents(path, &block) path << self unless @left_expr.nil? block.call(@left_expr, path) @left_expr._pcore_all_contents(path, &block) end unless @right_expr.nil? block.call(@right_expr, path) @right_expr._pcore_all_contents(path, &block) end path.pop end def eql?(o) super && @operator.eql?(o.operator) end alias == eql? end class MatchExpression < BinaryExpression def self._pcore_type @_pcore_type ||= Types::PObjectType .new('Puppet::AST::MatchExpression', { 'parent' => BinaryExpression._pcore_type, 'attributes' => { 'operator' => Types::PEnumType.new(['!~', '=~']) } }) end def self.from_hash(init_hash) from_asserted_hash(Types::TypeAsserter.assert_instance_of('Puppet::AST::MatchExpression initializer', _pcore_type.init_hash_type, init_hash)) end def self.from_asserted_hash(init_hash) new( init_hash['locator'], init_hash['offset'], init_hash['length'], init_hash['left_expr'], init_hash['right_expr'], init_hash['operator']) end def self.create(locator, offset, length, left_expr, right_expr, operator) ta = Types::TypeAsserter attrs = _pcore_type.attributes(true) ta.assert_instance_of('Puppet::AST::Positioned[locator]', attrs['locator'].type, locator) ta.assert_instance_of('Puppet::AST::Positioned[offset]', attrs['offset'].type, offset) ta.assert_instance_of('Puppet::AST::Positioned[length]', attrs['length'].type, length) ta.assert_instance_of('Puppet::AST::BinaryExpression[left_expr]', attrs['left_expr'].type, left_expr) ta.assert_instance_of('Puppet::AST::BinaryExpression[right_expr]', attrs['right_expr'].type, right_expr) ta.assert_instance_of('Puppet::AST::MatchExpression[operator]', attrs['operator'].type, operator) new(locator, offset, length, left_expr, right_expr, operator) end attr_reader :operator def initialize(locator, offset, length, left_expr, right_expr, operator) super(locator, offset, length, left_expr, right_expr) @hash = @hash ^ operator.hash @operator = operator end def _pcore_init_hash result = super result['operator'] = @operator result end def _pcore_contents yield(@left_expr) unless @left_expr.nil? yield(@right_expr) unless @right_expr.nil? end def _pcore_all_contents(path, &block) path << self unless @left_expr.nil? block.call(@left_expr, path) @left_expr._pcore_all_contents(path, &block) end unless @right_expr.nil? block.call(@right_expr, path) @right_expr._pcore_all_contents(path, &block) end path.pop end def eql?(o) super && @operator.eql?(o.operator) end alias == eql? end class InExpression < BinaryExpression def self._pcore_type @_pcore_type ||= Types::PObjectType.new('Puppet::AST::InExpression', { 'parent' => BinaryExpression._pcore_type }) end def _pcore_contents yield(@left_expr) unless @left_expr.nil? yield(@right_expr) unless @right_expr.nil? end def _pcore_all_contents(path, &block) path << self unless @left_expr.nil? block.call(@left_expr, path) @left_expr._pcore_all_contents(path, &block) end unless @right_expr.nil? block.call(@right_expr, path) @right_expr._pcore_all_contents(path, &block) end path.pop end end class BooleanExpression < BinaryExpression def self._pcore_type @_pcore_type ||= Types::PObjectType.new('Puppet::AST::BooleanExpression', { 'parent' => BinaryExpression._pcore_type }) end def _pcore_contents yield(@left_expr) unless @left_expr.nil? yield(@right_expr) unless @right_expr.nil? end def _pcore_all_contents(path, &block) path << self unless @left_expr.nil? block.call(@left_expr, path) @left_expr._pcore_all_contents(path, &block) end unless @right_expr.nil? block.call(@right_expr, path) @right_expr._pcore_all_contents(path, &block) end path.pop end end class AndExpression < BooleanExpression def self._pcore_type @_pcore_type ||= Types::PObjectType.new('Puppet::AST::AndExpression', { 'parent' => BooleanExpression._pcore_type }) end def _pcore_contents yield(@left_expr) unless @left_expr.nil? yield(@right_expr) unless @right_expr.nil? end def _pcore_all_contents(path, &block) path << self unless @left_expr.nil? block.call(@left_expr, path) @left_expr._pcore_all_contents(path, &block) end unless @right_expr.nil? block.call(@right_expr, path) @right_expr._pcore_all_contents(path, &block) end path.pop end end class OrExpression < BooleanExpression def self._pcore_type @_pcore_type ||= Types::PObjectType.new('Puppet::AST::OrExpression', { 'parent' => BooleanExpression._pcore_type }) end def _pcore_contents yield(@left_expr) unless @left_expr.nil? yield(@right_expr) unless @right_expr.nil? end def _pcore_all_contents(path, &block) path << self unless @left_expr.nil? block.call(@left_expr, path) @left_expr._pcore_all_contents(path, &block) end unless @right_expr.nil? block.call(@right_expr, path) @right_expr._pcore_all_contents(path, &block) end path.pop end end class LiteralList < Expression def self._pcore_type @_pcore_type ||= Types::PObjectType .new('Puppet::AST::LiteralList', { 'parent' => Expression._pcore_type, 'attributes' => { 'values' => { 'type' => Types::PArrayType.new(Expression._pcore_type), 'value' => [] } } }) end def self.from_hash(init_hash) from_asserted_hash(Types::TypeAsserter.assert_instance_of('Puppet::AST::LiteralList initializer', _pcore_type.init_hash_type, init_hash)) end def self.from_asserted_hash(init_hash) new( init_hash['locator'], init_hash['offset'], init_hash['length'], init_hash.fetch('values') { _pcore_type['values'].value }) end def self.create(locator, offset, length, values = _pcore_type['values'].value) ta = Types::TypeAsserter attrs = _pcore_type.attributes(true) ta.assert_instance_of('Puppet::AST::Positioned[locator]', attrs['locator'].type, locator) ta.assert_instance_of('Puppet::AST::Positioned[offset]', attrs['offset'].type, offset) ta.assert_instance_of('Puppet::AST::Positioned[length]', attrs['length'].type, length) ta.assert_instance_of('Puppet::AST::LiteralList[values]', attrs['values'].type, values) new(locator, offset, length, values) end attr_reader :values def initialize(locator, offset, length, values = _pcore_type['values'].value) super(locator, offset, length) @hash = @hash ^ values.hash @values = values end def _pcore_init_hash result = super result['values'] = @values unless _pcore_type['values'].default_value?(@values) result end def _pcore_contents @values.each { |value| yield(value) } end def _pcore_all_contents(path, &block) path << self @values.each do |value| block.call(value, path) value._pcore_all_contents(path, &block) end path.pop end def eql?(o) super && @values.eql?(o.values) end alias == eql? end class KeyedEntry < Positioned def self._pcore_type @_pcore_type ||= Types::PObjectType .new('Puppet::AST::KeyedEntry', { 'parent' => Positioned._pcore_type, 'attributes' => { 'key' => Expression._pcore_type, 'value' => Expression._pcore_type } }) end def self.from_hash(init_hash) from_asserted_hash(Types::TypeAsserter.assert_instance_of('Puppet::AST::KeyedEntry initializer', _pcore_type.init_hash_type, init_hash)) end def self.from_asserted_hash(init_hash) new( init_hash['locator'], init_hash['offset'], init_hash['length'], init_hash['key'], init_hash['value']) end def self.create(locator, offset, length, key, value) ta = Types::TypeAsserter attrs = _pcore_type.attributes(true) ta.assert_instance_of('Puppet::AST::Positioned[locator]', attrs['locator'].type, locator) ta.assert_instance_of('Puppet::AST::Positioned[offset]', attrs['offset'].type, offset) ta.assert_instance_of('Puppet::AST::Positioned[length]', attrs['length'].type, length) ta.assert_instance_of('Puppet::AST::KeyedEntry[key]', attrs['key'].type, key) ta.assert_instance_of('Puppet::AST::KeyedEntry[value]', attrs['value'].type, value) new(locator, offset, length, key, value) end attr_reader :key attr_reader :value def initialize(locator, offset, length, key, value) super(locator, offset, length) @hash = @hash ^ key.hash ^ value.hash @key = key @value = value end def _pcore_init_hash result = super result['key'] = @key result['value'] = @value result end def _pcore_contents yield(@key) unless @key.nil? yield(@value) unless @value.nil? end def _pcore_all_contents(path, &block) path << self unless @key.nil? block.call(@key, path) @key._pcore_all_contents(path, &block) end unless @value.nil? block.call(@value, path) @value._pcore_all_contents(path, &block) end path.pop end def eql?(o) super && @key.eql?(o.key) && @value.eql?(o.value) end alias == eql? end class LiteralHash < Expression def self._pcore_type @_pcore_type ||= Types::PObjectType .new('Puppet::AST::LiteralHash', { 'parent' => Expression._pcore_type, 'attributes' => { 'entries' => {
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/data_provider.rb
lib/puppet/pops/lookup/data_provider.rb
# frozen_string_literal: true module Puppet::Pops module Lookup # @api private module DataProvider def self.key_type @key_type end def self.value_type @value_type end def self.register_types(loader) tp = Types::TypeParser.singleton @key_type = tp.parse('RichDataKey', loader) @value_type = tp.parse('RichData', loader) end # Performs a lookup with an endless recursion check. # # @param key [LookupKey] The key to lookup # @param lookup_invocation [Invocation] The current lookup invocation # @param merge [MergeStrategy,String,Hash{String=>Object},nil] Merge strategy or hash with strategy and options # def key_lookup(key, lookup_invocation, merge) lookup_invocation.check(key.to_s) { unchecked_key_lookup(key, lookup_invocation, merge) } end # Performs a lookup using a module default hierarchy with an endless recursion check. All providers except # the `ModuleDataProvider` will throw `:no_such_key` if this method is called. # # @param key [LookupKey] The key to lookup # @param lookup_invocation [Invocation] The current lookup invocation # @param merge [MergeStrategy,String,Hash{String=>Object},nil] Merge strategy or hash with strategy and options # def key_lookup_in_default(key, lookup_invocation, merge) throw :no_such_key end def lookup(key, lookup_invocation, merge) lookup_invocation.check(key.to_s) { unchecked_key_lookup(key, lookup_invocation, merge) } end # Performs a lookup with the assumption that a recursive check has been made. # # @param key [LookupKey] The key to lookup # @param lookup_invocation [Invocation] The current lookup invocation # @param merge [MergeStrategy,String,Hash{String => Object},nil] Merge strategy, merge strategy name, strategy and options hash, or nil (implies "first found") # @return [Object] the found object # @throw :no_such_key when the object is not found def unchecked_key_lookup(key, lookup_invocation, merge) raise NotImplementedError, "Subclass of #{DataProvider.name} must implement 'unchecked_lookup' method" end # @return [String,nil] the name of the module that this provider belongs to nor `nil` if it doesn't belong to a module def module_name nil end # @return [String] the name of the this data provider def name raise NotImplementedError, "Subclass of #{DataProvider.name} must implement 'name' method" end # @returns `true` if the value provided by this instance can always be trusted, `false` otherwise def value_is_validated? false end # Asserts that _data_hash_ is a hash. Will yield to obtain origin of value in case an error is produced # # @param data_hash [Hash{String=>Object}] The data hash # @return [Hash{String=>Object}] The data hash def validate_data_hash(data_hash, &block) Types::TypeAsserter.assert_instance_of(nil, Types::PHashType::DEFAULT, data_hash, &block) end # Asserts that _data_value_ is of valid type. Will yield to obtain origin of value in case an error is produced # # @param data_provider [DataProvider] The data provider that produced the hash # @return [Object] The data value def validate_data_value(value, &block) # The DataProvider.value_type is self recursive so further recursive check of collections is needed here unless value_is_validated? || DataProvider.value_type.instance?(value) actual_type = Types::TypeCalculator.singleton.infer(value) raise Types::TypeAssertionError.new("#{yield} has wrong type, expects Puppet::LookupValue, got #{actual_type}", DataProvider.value_type, actual_type) end value end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/function_provider.rb
lib/puppet/pops/lookup/function_provider.rb
# frozen_string_literal: true require_relative 'data_adapter' require_relative 'context' require_relative 'data_provider' module Puppet::Pops module Lookup # @api private class FunctionProvider include DataProvider attr_reader :parent_data_provider, :function_name, :locations # Returns the type that all the return type of all functions must be assignable to. # For `lookup_key` and `data_dig`, that will be the `Puppet::LookupValue` type. For # `data_hash` it will be a Hash[Puppet::LookupKey,Puppet::LookupValue]` # # @return [Type] the trusted return type def self.trusted_return_type DataProvider.value_type end def initialize(name, parent_data_provider, function_name, options, locations) @name = name @parent_data_provider = parent_data_provider @function_name = function_name @options = options @locations = locations || [nil] @contexts = {} end # @return [FunctionContext] the function context associated with this provider def function_context(lookup_invocation, location) @contexts[location] ||= create_function_context(lookup_invocation) end def create_function_context(lookup_invocation) FunctionContext.new(EnvironmentContext.adapt(lookup_invocation.scope.compiler.environment), module_name, function(lookup_invocation)) end def module_name @parent_data_provider.module_name end def name "Hierarchy entry \"#{@name}\"" end def full_name "#{self.class::TAG} function '#{@function_name}'" end def to_s name end # Obtains the options to send to the function, optionally merged with a 'path' or 'uri' option # # @param [Pathname,URI] location The location to add to the options # @return [Hash{String => Object}] The options hash def options(location = nil) location = location.location unless location.nil? case location when Pathname @options.merge(HieraConfig::KEY_PATH => location.to_s) when URI @options.merge(HieraConfig::KEY_URI => location.to_s) else @options end end def value_is_validated? @value_is_validated end private def function(lookup_invocation) @function ||= load_function(lookup_invocation) end def load_function(lookup_invocation) loaders = lookup_invocation.scope.compiler.loaders typed_name = Loader::TypedName.new(:function, @function_name) loader = if typed_name.qualified? qualifier = typed_name.name_parts[0] qualifier == 'environment' ? loaders.private_environment_loader : loaders.private_loader_for_module(qualifier) else loaders.private_environment_loader end te = loader.load_typed(typed_name) if te.nil? || te.value.nil? @parent_data_provider.config(lookup_invocation).fail(Issues::HIERA_DATA_PROVIDER_FUNCTION_NOT_FOUND, :function_type => self.class::TAG, :function_name => @function_name) end func = te.value @value_is_validated = func.class.dispatcher.dispatchers.all? do |dispatcher| rt = dispatcher.type.return_type if rt.nil? false else Types::TypeAsserter.assert_assignable(nil, self.class.trusted_return_type, rt) { "Return type of '#{self.class::TAG}' function named '#{function_name}'" } true end end func end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/interpolation.rb
lib/puppet/pops/lookup/interpolation.rb
# frozen_string_literal: true require 'hiera/scope' require_relative 'sub_lookup' module Puppet::Pops module Lookup # Adds support for interpolation expressions. The expressions may contain keys that uses dot-notation # to further navigate into hashes and arrays # # @api public module Interpolation include SubLookup # @param value [Object] The value to interpolate # @param context [Context] The current lookup context # @param allow_methods [Boolean] `true` if interpolation expression that contains lookup methods are allowed # @return [Object] the result of resolving all interpolations in the given value # @api public def interpolate(value, context, allow_methods) case value when String value.index('%{').nil? ? value : interpolate_string(value, context, allow_methods) when Array value.map { |element| interpolate(element, context, allow_methods) } when Hash result = {} value.each_pair { |k, v| result[interpolate(k, context, allow_methods)] = interpolate(v, context, allow_methods) } result else value end end private EMPTY_INTERPOLATIONS = { '' => true, '::' => true, '""' => true, "''" => true, '"::"' => true, "'::'" => true }.freeze # Matches a key that is quoted using a matching pair of either single or double quotes. QUOTED_KEY = /^(?:"([^"]+)"|'([^']+)')$/ def interpolate_string(subject, context, allow_methods) lookup_invocation = context.is_a?(Invocation) ? context : context.invocation lookup_invocation.with(:interpolate, subject) do subject.gsub(/%\{([^}]*)\}/) do |match| expr = ::Regexp.last_match(1) # Leading and trailing spaces inside an interpolation expression are insignificant expr.strip! value = nil unless EMPTY_INTERPOLATIONS[expr] method_key, key = get_method_and_data(expr, allow_methods) is_alias = method_key == :alias # Alias is only permitted if the entire string is equal to the interpolate expression fail(Issues::HIERA_INTERPOLATION_ALIAS_NOT_ENTIRE_STRING) if is_alias && subject != match value = interpolate_method(method_key).call(key, lookup_invocation, subject) # break gsub and return value immediately if this was an alias substitution. The value might be something other than a String return value if is_alias value = lookup_invocation.check(method_key == :scope ? "scope:#{key}" : key) { interpolate(value, lookup_invocation, allow_methods) } end value.nil? ? '' : value end end end def interpolate_method(method_key) @@interpolate_methods ||= begin global_lookup = lambda do |key, lookup_invocation, _| scope = lookup_invocation.scope if scope.is_a?(Hiera::Scope) && !lookup_invocation.global_only? # "unwrap" the Hiera::Scope scope = scope.real end lookup_invocation.with_scope(scope) do |sub_invocation| sub_invocation.lookup(key) { Lookup.lookup(key, nil, '', true, nil, sub_invocation) } end end scope_lookup = lambda do |key, lookup_invocation, subject| segments = split_key(key) { |problem| Puppet::DataBinding::LookupError.new("#{problem} in string: #{subject}") } root_key = segments.shift value = lookup_invocation.with(:scope, 'Global Scope') do ovr = lookup_invocation.override_values if ovr.include?(root_key) lookup_invocation.report_found_in_overrides(root_key, ovr[root_key]) else scope = lookup_invocation.scope val = nil if (default_key_exists = lookup_invocation.default_values.include?(root_key)) catch(:undefined_variable) { val = scope[root_key] } else val = scope[root_key] end if val.nil? && !nil_in_scope?(scope, root_key) if default_key_exists lookup_invocation.report_found_in_defaults(root_key, lookup_invocation.default_values[root_key]) else nil end else lookup_invocation.report_found(root_key, val) end end end unless value.nil? || segments.empty? found = nil; catch(:no_such_key) { found = sub_lookup(key, lookup_invocation, segments, value) } value = found; end lookup_invocation.remember_scope_lookup(key, root_key, segments, value) value end { :lookup => global_lookup, :hiera => global_lookup, # this is just an alias for 'lookup' :alias => global_lookup, # same as 'lookup' but expression must be entire string and result is not subject to string substitution :scope => scope_lookup, :literal => ->(key, _, _) { key } }.freeze end interpolate_method = @@interpolate_methods[method_key] fail(Issues::HIERA_INTERPOLATION_UNKNOWN_INTERPOLATION_METHOD, :name => method_key) unless interpolate_method interpolate_method end # Because the semantics of Puppet::Parser::Scope#include? differs from Hash#include? def nil_in_scope?(scope, key) if scope.is_a?(Hash) scope.include?(key) else scope.exist?(key) end end def get_method_and_data(data, allow_methods) match = data.match(/^(\w+)\((?:"([^"]+)"|'([^']+)')\)$/) if match fail(Issues::HIERA_INTERPOLATION_METHOD_SYNTAX_NOT_ALLOWED) unless allow_methods key = match[1].to_sym data = match[2] || match[3] # double or single qouted else key = :scope end [key, data] end def fail(issue, args = EMPTY_HASH) raise Puppet::DataBinding::LookupError.new( issue.format(args), nil, nil, nil, nil, issue.issue_code ) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/global_data_provider.rb
lib/puppet/pops/lookup/global_data_provider.rb
# frozen_string_literal: true require 'hiera/scope' require_relative 'configured_data_provider' module Puppet::Pops module Lookup # @api private class GlobalDataProvider < ConfiguredDataProvider def place 'Global' end def unchecked_key_lookup(key, lookup_invocation, merge) config = config(lookup_invocation) if config.version == 3 # Hiera version 3 needs access to special scope variables scope = lookup_invocation.scope unless scope.is_a?(Hiera::Scope) return lookup_invocation.with_scope(Hiera::Scope.new(scope)) do |hiera_invocation| # Confine to global scope unless an environment data provider has been defined (same as for hiera_xxx functions) adapter = lookup_invocation.lookup_adapter hiera_invocation.set_global_only unless adapter.global_only? || adapter.has_environment_data_provider?(lookup_invocation) hiera_invocation.lookup(key, lookup_invocation.module_name) { unchecked_key_lookup(key, hiera_invocation, merge) } end end merge = MergeStrategy.strategy(merge) unless config.merge_strategy.is_a?(DefaultMergeStrategy) if lookup_invocation.hiera_xxx_call? && merge.is_a?(HashMergeStrategy) # Merge strategy defined in the hiera config only applies when the call stems from a hiera_hash call. merge = config.merge_strategy lookup_invocation.set_hiera_v3_merge_behavior end end value = super(key, lookup_invocation, merge) if lookup_invocation.hiera_xxx_call? if merge.is_a?(HashMergeStrategy) || merge.is_a?(DeepMergeStrategy) # hiera_hash calls should error when found values are not hashes Types::TypeAsserter.assert_instance_of('value', Types::PHashType::DEFAULT, value) end if !key.segments.nil? && (merge.is_a?(HashMergeStrategy) || merge.is_a?(UniqueMergeStrategy)) strategy = merge.is_a?(HashMergeStrategy) ? 'hash' : 'array' # Fail with old familiar message from Hiera 3 raise Puppet::DataBinding::LookupError, "Resolution type :#{strategy} is illegal when accessing values using dotted keys. Offending key was '#{key}'" end end value else super end end protected def assert_config_version(config) config.fail(Issues::HIERA_UNSUPPORTED_VERSION_IN_GLOBAL) if config.version == 4 config end # Return the root of the environment # # @param lookup_invocation [Invocation] The current lookup invocation # @return [Pathname] Path to the parent of the hiera configuration file def provider_root(lookup_invocation) configuration_path(lookup_invocation).parent end def configuration_path(lookup_invocation) lookup_invocation.global_hiera_config_path end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/data_dig_function_provider.rb
lib/puppet/pops/lookup/data_dig_function_provider.rb
# frozen_string_literal: true require_relative 'function_provider' module Puppet::Pops module Lookup # @api private class DataDigFunctionProvider < FunctionProvider TAG = 'data_dig' # Performs a lookup with the assumption that a recursive check has been made. # # @param key [LookupKey] The key to lookup # @param lookup_invocation [Invocation] The current lookup invocation # @param merge [MergeStrategy,String,Hash{String => Object},nil] Merge strategy, merge strategy name, strategy and options hash, or nil (implies "first found") # @return [Object] the found object # @throw :no_such_key when the object is not found def unchecked_key_lookup(key, lookup_invocation, merge) lookup_invocation.with(:data_provider, self) do MergeStrategy.strategy(merge).lookup(locations, lookup_invocation) do |location| invoke_with_location(lookup_invocation, location, key, merge) end end end def invoke_with_location(lookup_invocation, location, key, merge) if location.nil? key.undig(lookup_invocation.report_found(key, validated_data_dig(key, lookup_invocation, nil, merge))) else lookup_invocation.with(:location, location) do key.undig(lookup_invocation.report_found(key, validated_data_dig(key, lookup_invocation, location, merge))) end end end def label 'Data Dig' end def validated_data_dig(key, lookup_invocation, location, merge) validate_data_value(data_dig(key, lookup_invocation, location, merge)) do msg = "Value for key '#{key}', returned from #{full_name}" location.nil? ? msg : "#{msg}, when using location '#{location}'," end end private def data_dig(key, lookup_invocation, location, merge) unless location.nil? || location.exist? lookup_invocation.report_location_not_found throw :no_such_key end ctx = function_context(lookup_invocation, location) ctx.data_hash ||= {} catch(:no_such_key) do hash = ctx.data_hash hash[key] = ctx.function.call(lookup_invocation.scope, key.to_a, options(location), Context.new(ctx, lookup_invocation)) unless hash.include?(key) return hash[key] end lookup_invocation.report_not_found(key) throw :no_such_key end end # @api private class V3BackendFunctionProvider < DataDigFunctionProvider TAG = 'hiera3_backend' def data_dig(key, lookup_invocation, location, merge) @backend ||= instantiate_backend(lookup_invocation) # A merge_behavior retrieved from hiera.yaml must not be converted here. Instead, passing the symbol :hash # tells the V3 backend to pick it up from the config. resolution_type = lookup_invocation.hiera_v3_merge_behavior? ? :hash : convert_merge(merge) @backend.lookup(key.to_s, lookup_invocation.scope, lookup_invocation.hiera_v3_location_overrides, resolution_type, { :recurse_guard => nil }) end def full_name "hiera version 3 backend '#{options[HieraConfig::KEY_BACKEND]}'" end def value_is_validated? false end private def instantiate_backend(lookup_invocation) backend_name = options[HieraConfig::KEY_BACKEND] begin require 'hiera/backend' require "hiera/backend/#{backend_name.downcase}_backend" backend = Hiera::Backend.const_get("#{backend_name.capitalize}_backend").new backend.method(:lookup).arity == 4 ? Hiera::Backend::Backend1xWrapper.new(backend) : backend rescue LoadError => e lookup_invocation.report_text { "Unable to load backend '#{backend_name}': #{e.message}" } throw :no_such_key rescue NameError => e lookup_invocation.report_text { "Unable to instantiate backend '#{backend_name}': #{e.message}" } throw :no_such_key end end # Converts a lookup 'merge' parameter argument into a Hiera 'resolution_type' argument. # # @param merge [String,Hash,nil] The lookup 'merge' argument # @return [Symbol,Hash,nil] The Hiera 'resolution_type' def convert_merge(merge) case merge when nil, 'first', 'default' # Nil is OK. Defaults to Hiera :priority nil when Puppet::Pops::MergeStrategy convert_merge(merge.configuration) when 'unique' # Equivalent to Hiera :array :array when 'hash' # Equivalent to Hiera :hash with default :native merge behavior. A Hash must be passed here # to override possible Hiera deep merge config settings. { :behavior => :native } when 'deep', 'unconstrained_deep' # Equivalent to Hiera :hash with :deeper merge behavior. { :behavior => :deeper } when 'reverse_deep' # Equivalent to Hiera :hash with :deep merge behavior. { :behavior => :deep } when Hash strategy = merge['strategy'] case strategy when 'deep', 'unconstrained_deep', 'reverse_deep' result = { :behavior => strategy == 'reverse_deep' ? :deep : :deeper } # Remaining entries must have symbolic keys merge.each_pair { |k, v| result[k.to_sym] = v unless k == 'strategy' } result else convert_merge(strategy) end else raise Puppet::DataBinding::LookupError, "Unrecognized value for request 'merge' parameter: '#{merge}'" end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/lookup_key_function_provider.rb
lib/puppet/pops/lookup/lookup_key_function_provider.rb
# frozen_string_literal: true require_relative 'function_provider' module Puppet::Pops module Lookup # @api private class LookupKeyFunctionProvider < FunctionProvider TAG = 'lookup_key' # Performs a lookup with the assumption that a recursive check has been made. # # @param key [LookupKey] The key to lookup # @param lookup_invocation [Invocation] The current lookup invocation # @param merge [MergeStrategy,String,Hash{String => Object},nil] Merge strategy, merge strategy name, strategy and options hash, or nil (implies "first found") # @return [Object] the found object # @throw :no_such_key when the object is not found def unchecked_key_lookup(key, lookup_invocation, merge) root_key = key.root_key lookup_invocation.with(:data_provider, self) do MergeStrategy.strategy(merge).lookup(locations, lookup_invocation) do |location| invoke_with_location(lookup_invocation, location, root_key, merge) end end end def invoke_with_location(lookup_invocation, location, root_key, merge) if location.nil? value = lookup_key(root_key, lookup_invocation, nil, merge) lookup_invocation.report_found(root_key, value) else lookup_invocation.with(:location, location) do value = lookup_key(root_key, lookup_invocation, location, merge) lookup_invocation.report_found(root_key, value) end end end def label 'Lookup Key' end private def lookup_key(key, lookup_invocation, location, merge) unless location.nil? || location.exist? lookup_invocation.report_location_not_found throw :no_such_key end ctx = function_context(lookup_invocation, location) ctx.data_hash ||= {} catch(:no_such_key) do hash = ctx.data_hash unless hash.include?(key) hash[key] = validate_data_value(ctx.function.call(lookup_invocation.scope, key, options(location), Context.new(ctx, lookup_invocation))) do msg = "Value for key '#{key}', returned from #{full_name}" location.nil? ? msg : "#{msg}, when using location '#{location}'," end end return hash[key] end lookup_invocation.report_not_found(key) throw :no_such_key end end # @api private class V3LookupKeyFunctionProvider < LookupKeyFunctionProvider TAG = 'v3_lookup_key' def initialize(name, parent_data_provider, function_name, options, locations) @datadir = options.delete(HieraConfig::KEY_DATADIR) super end def unchecked_key_lookup(key, lookup_invocation, merge) extra_paths = lookup_invocation.hiera_v3_location_overrides if extra_paths.nil? || extra_paths.empty? super else # Extra paths provided. Must be resolved and placed in front of known paths paths = parent_data_provider.config(lookup_invocation).resolve_paths(@datadir, extra_paths, lookup_invocation, false, ".#{@name}") all_locations = paths + locations root_key = key.root_key lookup_invocation.with(:data_provider, self) do MergeStrategy.strategy(merge).lookup(all_locations, lookup_invocation) do |location| invoke_with_location(lookup_invocation, location, root_key, merge) end end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/lookup_adapter.rb
lib/puppet/pops/lookup/lookup_adapter.rb
# frozen_string_literal: true require_relative 'data_adapter' require_relative 'lookup_key' module Puppet::Pops module Lookup # A LookupAdapter is a specialized DataAdapter that uses its hash to store data providers. It also remembers the compiler # that it is attached to and maintains a cache of _lookup options_ retrieved from the data providers associated with the # compiler's environment. # # @api private class LookupAdapter < DataAdapter LOOKUP_OPTIONS_PREFIX = LOOKUP_OPTIONS + '.' LOOKUP_OPTIONS_PREFIX.freeze LOOKUP_OPTIONS_PATTERN_START = '^' HASH = 'hash' MERGE = 'merge' CONVERT_TO = 'convert_to' NEW = 'new' def self.create_adapter(compiler) new(compiler) end def initialize(compiler) super() @compiler = compiler @lookup_options = {} # Get a KeyRecorder from context, and set a "null recorder" if not defined @key_recorder = Puppet.lookup(:lookup_key_recorder) { KeyRecorder.singleton } end # Performs a lookup using global, environment, and module data providers. Merge the result using the given # _merge_ strategy. If the merge strategy is nil, then an attempt is made to find merge options in the # `lookup_options` hash for an entry associated with the key. If no options are found, the no merge is performed # and the first found entry is returned. # # @param key [String] The key to lookup # @param lookup_invocation [Invocation] the lookup invocation # @param merge [MergeStrategy,String,Hash{String => Object},nil] Merge strategy, merge strategy name, strategy and options hash, or nil (implies "first found") # @return [Object] the found object # @throw :no_such_key when the object is not found # def lookup(key, lookup_invocation, merge) # The 'lookup_options' key is reserved and not found as normal data if key == LOOKUP_OPTIONS || key.start_with?(LOOKUP_OPTIONS_PREFIX) lookup_invocation.with(:invalid_key, LOOKUP_OPTIONS) do throw :no_such_key end end # Record that the key was looked up. This will record all keys for which a lookup is performed # except 'lookup_options' (since that is illegal from a user perspective, # and from an impact perspective is always looked up). @key_recorder.record(key) key = LookupKey.new(key) lookup_invocation.lookup(key, key.module_name) do if lookup_invocation.only_explain_options? catch(:no_such_key) { do_lookup(LookupKey::LOOKUP_OPTIONS, lookup_invocation, HASH) } nil else lookup_options = lookup_lookup_options(key, lookup_invocation) || {} if merge.nil? # Used cached lookup_options # merge = lookup_merge_options(key, lookup_invocation) merge = lookup_options[MERGE] lookup_invocation.report_merge_source(LOOKUP_OPTIONS) unless merge.nil? end convert_result(key.to_s, lookup_options, lookup_invocation, lambda do lookup_invocation.with(:data, key.to_s) do catch(:no_such_key) { return do_lookup(key, lookup_invocation, merge) } throw :no_such_key if lookup_invocation.global_only? key.dig(lookup_invocation, lookup_default_in_module(key, lookup_invocation)) end end) end end end # Performs a possible conversion of the result of calling `the_lookup` lambda # The conversion takes place if there is a 'convert_to' key in the lookup_options # If there is no conversion, the result of calling `the_lookup` is returned # otherwise the successfully converted value. # Errors are raised if the convert_to is faulty (bad type string, or if a call to # new(T, <args>) fails. # # @param key [String] The key to lookup # @param lookup_options [Hash] a hash of options # @param lookup_invocation [Invocation] the lookup invocation # @param the_lookup [Lambda] zero arg lambda that performs the lookup of a value # @return [Object] the looked up value, or converted value if there was conversion # @throw :no_such_key when the object is not found (if thrown by `the_lookup`) # def convert_result(key, lookup_options, lookup_invocation, the_lookup) result = the_lookup.call convert_to = lookup_options[CONVERT_TO] return result if convert_to.nil? convert_to = convert_to.is_a?(Array) ? convert_to : [convert_to] if convert_to[0].is_a?(String) begin convert_to[0] = Puppet::Pops::Types::TypeParser.singleton.parse(convert_to[0]) rescue StandardError => e raise Puppet::DataBinding::LookupError, _("Invalid data type in lookup_options for key '%{key}' could not parse '%{source}', error: '%{msg}") % { key: key, source: convert_to[0], msg: e.message } end end begin result = lookup_invocation.scope.call_function(NEW, [convert_to[0], result, *convert_to[1..]]) # TRANSLATORS 'lookup_options', 'convert_to' and args_string variable should not be translated, args_string = Puppet::Pops::Types::StringConverter.singleton.convert(convert_to) lookup_invocation.report_text { _("Applying convert_to lookup_option with arguments %{args}") % { args: args_string } } rescue StandardError => e raise Puppet::DataBinding::LookupError, _("The convert_to lookup_option for key '%{key}' raised error: %{msg}") % { key: key, msg: e.message } end result end def lookup_global(key, lookup_invocation, merge_strategy) # hiera_xxx will always use global_provider regardless of data_binding_terminus setting terminus = lookup_invocation.hiera_xxx_call? ? :hiera : Puppet[:data_binding_terminus] case terminus when :hiera, 'hiera' provider = global_provider(lookup_invocation) throw :no_such_key if provider.nil? provider.key_lookup(key, lookup_invocation, merge_strategy) when :none, 'none', '', nil # If global lookup is disabled, immediately report as not found lookup_invocation.report_not_found(key) throw :no_such_key else lookup_invocation.with(:global, terminus) do catch(:no_such_key) do return lookup_invocation.report_found(key, Puppet::DataBinding.indirection.find(key.root_key, { :environment => environment, :variables => lookup_invocation.scope, :merge => merge_strategy })) end lookup_invocation.report_not_found(key) throw :no_such_key end end rescue Puppet::DataBinding::LookupError => detail raise detail unless detail.issue_code.nil? error = Puppet::Error.new(_("Lookup of key '%{key}' failed: %{detail}") % { key: lookup_invocation.top_key, detail: detail.message }) error.set_backtrace(detail.backtrace) raise error end def lookup_in_environment(key, lookup_invocation, merge_strategy) provider = env_provider(lookup_invocation) throw :no_such_key if provider.nil? provider.key_lookup(key, lookup_invocation, merge_strategy) end def lookup_in_module(key, lookup_invocation, merge_strategy) module_name = lookup_invocation.module_name # Do not attempt to do a lookup in a module unless the name is qualified. throw :no_such_key if module_name.nil? provider = module_provider(lookup_invocation, module_name) if provider.nil? if environment.module(module_name).nil? lookup_invocation.report_module_not_found(module_name) else lookup_invocation.report_module_provider_not_found(module_name) end throw :no_such_key end provider.key_lookup(key, lookup_invocation, merge_strategy) end def lookup_default_in_module(key, lookup_invocation) module_name = lookup_invocation.module_name # Do not attempt to do a lookup in a module unless the name is qualified. throw :no_such_key if module_name.nil? provider = module_provider(lookup_invocation, module_name) throw :no_such_key if provider.nil? || !provider.config(lookup_invocation).has_default_hierarchy? lookup_invocation.with(:scope, "Searching default_hierarchy of module \"#{module_name}\"") do merge_strategy = nil if merge_strategy.nil? @module_default_lookup_options ||= {} options = @module_default_lookup_options.fetch(module_name) do |k| meta_invocation = Invocation.new(lookup_invocation.scope) meta_invocation.lookup(LookupKey::LOOKUP_OPTIONS, k) do opts = nil lookup_invocation.with(:scope, "Searching for \"#{LookupKey::LOOKUP_OPTIONS}\"") do catch(:no_such_key) do opts = compile_patterns( validate_lookup_options( provider.key_lookup_in_default(LookupKey::LOOKUP_OPTIONS, meta_invocation, MergeStrategy.strategy(HASH)), k ) ) end end @module_default_lookup_options[k] = opts end end lookup_options = extract_lookup_options_for_key(key, options) merge_strategy = lookup_options[MERGE] unless lookup_options.nil? end lookup_invocation.with(:scope, "Searching for \"#{key}\"") do provider.key_lookup_in_default(key, lookup_invocation, merge_strategy) end end end # Retrieve the merge options that match the given `name`. # # @param key [LookupKey] The key for which we want merge options # @param lookup_invocation [Invocation] the lookup invocation # @return [String,Hash,nil] The found merge options or nil # def lookup_merge_options(key, lookup_invocation) lookup_options = lookup_lookup_options(key, lookup_invocation) lookup_options.nil? ? nil : lookup_options[MERGE] end # Retrieve the lookup options that match the given `name`. # # @param key [LookupKey] The key for which we want lookup options # @param lookup_invocation [Puppet::Pops::Lookup::Invocation] the lookup invocation # @return [String,Hash,nil] The found lookup options or nil # def lookup_lookup_options(key, lookup_invocation) module_name = key.module_name # Retrieve the options for the module. We use nil as a key in case we have no module if !@lookup_options.include?(module_name) options = retrieve_lookup_options(module_name, lookup_invocation, MergeStrategy.strategy(HASH)) @lookup_options[module_name] = options else options = @lookup_options[module_name] end extract_lookup_options_for_key(key, options) end def extract_lookup_options_for_key(key, options) return nil if options.nil? rk = key.root_key key_opts = options[0] unless key_opts.nil? key_opt = key_opts[rk] return key_opt unless key_opt.nil? end patterns = options[1] patterns.each_pair { |pattern, value| return value if pattern =~ rk } unless patterns.nil? nil end # @param lookup_invocation [Puppet::Pops::Lookup::Invocation] the lookup invocation # @return [Boolean] `true` if an environment data provider version 5 is configured def has_environment_data_provider?(lookup_invocation) ep = env_provider(lookup_invocation) ep.nil? ? false : ep.config(lookup_invocation).version >= 5 end # @return [Pathname] the full path of the hiera.yaml config file def global_hiera_config_path @global_hiera_config_path ||= Pathname.new(Puppet.settings[:hiera_config]) end # @param path [String] the absolute path name of the global hiera.yaml file. # @return [LookupAdapter] self def set_global_hiera_config_path(path) @global_hiera_config_path = Pathname.new(path) self end def global_only? instance_variable_defined?(:@global_only) ? @global_only : false end # Instructs the lookup framework to only perform lookups in the global layer # @return [LookupAdapter] self def set_global_only @global_only = true self end private PROVIDER_STACK = [:lookup_global, :lookup_in_environment, :lookup_in_module].freeze def validate_lookup_options(options, module_name) return nil if options.nil? raise Puppet::DataBinding::LookupError, _("value of %{opts} must be a hash") % { opts: LOOKUP_OPTIONS } unless options.is_a?(Hash) return options if module_name.nil? pfx = "#{module_name}::" options.each_pair do |key, _value| if key.start_with?(LOOKUP_OPTIONS_PATTERN_START) unless key[1..pfx.length] == pfx raise Puppet::DataBinding::LookupError, _("all %{opts} patterns must match a key starting with module name '%{module_name}'") % { opts: LOOKUP_OPTIONS, module_name: module_name } end else unless key.start_with?(pfx) raise Puppet::DataBinding::LookupError, _("all %{opts} keys must start with module name '%{module_name}'") % { opts: LOOKUP_OPTIONS, module_name: module_name } end end end end def compile_patterns(options) return nil if options.nil? key_options = {} pattern_options = {} options.each_pair do |key, value| if key.start_with?(LOOKUP_OPTIONS_PATTERN_START) pattern_options[Regexp.compile(key)] = value else key_options[key] = value end end [key_options.empty? ? nil : key_options, pattern_options.empty? ? nil : pattern_options] end def do_lookup(key, lookup_invocation, merge) if lookup_invocation.global_only? key.dig(lookup_invocation, lookup_global(key, lookup_invocation, merge)) else merge_strategy = Puppet::Pops::MergeStrategy.strategy(merge) key.dig(lookup_invocation, merge_strategy.lookup(PROVIDER_STACK, lookup_invocation) { |m| send(m, key, lookup_invocation, merge_strategy) }) end end GLOBAL_ENV_MERGE = 'Global and Environment' # Retrieve lookup options that applies when using a specific module (i.e. a merge of the pre-cached # `env_lookup_options` and the module specific data) def retrieve_lookup_options(module_name, lookup_invocation, merge_strategy) meta_invocation = Invocation.new(lookup_invocation.scope) meta_invocation.lookup(LookupKey::LOOKUP_OPTIONS, lookup_invocation.module_name) do meta_invocation.with(:meta, LOOKUP_OPTIONS) do if meta_invocation.global_only? compile_patterns(global_lookup_options(meta_invocation, merge_strategy)) else opts = env_lookup_options(meta_invocation, merge_strategy) unless module_name.nil? # Store environment options at key nil. This removes the need for an additional lookup for keys that are not prefixed. @lookup_options[nil] = compile_patterns(opts) unless @lookup_options.include?(nil) catch(:no_such_key) do module_opts = validate_lookup_options(lookup_in_module(LookupKey::LOOKUP_OPTIONS, meta_invocation, merge_strategy), module_name) opts = if opts.nil? module_opts elsif module_opts merge_strategy.lookup([GLOBAL_ENV_MERGE, "Module #{lookup_invocation.module_name}"], meta_invocation) do |n| meta_invocation.with(:scope, n) { meta_invocation.report_found(LOOKUP_OPTIONS, n == GLOBAL_ENV_MERGE ? opts : module_opts) } end end end end compile_patterns(opts) end end end end # Retrieve and cache the global lookup options def global_lookup_options(lookup_invocation, merge_strategy) unless instance_variable_defined?(:@global_lookup_options) @global_lookup_options = nil catch(:no_such_key) { @global_lookup_options = validate_lookup_options(lookup_global(LookupKey::LOOKUP_OPTIONS, lookup_invocation, merge_strategy), nil) } end @global_lookup_options end # Retrieve and cache lookup options specific to the environment of the compiler that this adapter is attached to (i.e. a merge # of global and environment lookup options). def env_lookup_options(lookup_invocation, merge_strategy) unless instance_variable_defined?(:@env_lookup_options) global_options = global_lookup_options(lookup_invocation, merge_strategy) @env_only_lookup_options = nil catch(:no_such_key) { @env_only_lookup_options = validate_lookup_options(lookup_in_environment(LookupKey::LOOKUP_OPTIONS, lookup_invocation, merge_strategy), nil) } if global_options.nil? @env_lookup_options = @env_only_lookup_options elsif @env_only_lookup_options.nil? @env_lookup_options = global_options else @env_lookup_options = merge_strategy.merge(global_options, @env_only_lookup_options) end end @env_lookup_options end def global_provider(lookup_invocation) @global_provider = GlobalDataProvider.new unless instance_variable_defined?(:@global_provider) @global_provider end def env_provider(lookup_invocation) @env_provider = initialize_env_provider(lookup_invocation) unless instance_variable_defined?(:@env_provider) @env_provider end def module_provider(lookup_invocation, module_name) # Test if the key is present for the given module_name. It might be there even if the # value is nil (which indicates that no module provider is configured for the given name) unless include?(module_name) self[module_name] = initialize_module_provider(lookup_invocation, module_name) end self[module_name] end def initialize_module_provider(lookup_invocation, module_name) mod = environment.module(module_name) return nil if mod.nil? metadata = mod.metadata provider_name = metadata.nil? ? nil : metadata['data_provider'] mp = nil if mod.has_hiera_conf? mp = ModuleDataProvider.new(module_name) # A version 5 hiera.yaml trumps a data provider setting in the module mp_config = mp.config(lookup_invocation) if mp_config.nil? mp = nil elsif mp_config.version >= 5 unless provider_name.nil? || Puppet[:strict] == :off Puppet.warn_once('deprecations', "metadata.json#data_provider-#{module_name}", _("Defining \"data_provider\": \"%{name}\" in metadata.json is deprecated. It is ignored since a '%{config}' with version >= 5 is present") % { name: provider_name, config: HieraConfig::CONFIG_FILE_NAME }, mod.metadata_file) end provider_name = nil end end if provider_name.nil? mp else unless Puppet[:strict] == :off msg = _("Defining \"data_provider\": \"%{name}\" in metadata.json is deprecated.") % { name: provider_name } msg += " " + _("A '%{hiera_config}' file should be used instead") % { hiera_config: HieraConfig::CONFIG_FILE_NAME } if mp.nil? Puppet.warn_once('deprecations', "metadata.json#data_provider-#{module_name}", msg, mod.metadata_file) end case provider_name when 'none' nil when 'hiera' mp || ModuleDataProvider.new(module_name) when 'function' mp = ModuleDataProvider.new(module_name) mp.config = HieraConfig.v4_function_config(Pathname(mod.path), "#{module_name}::data", mp) mp else raise Puppet::Error.new(_("Environment '%{env}', cannot find module_data_provider '%{provider}'")) % { env: environment.name, provider: provider_name } end end end def initialize_env_provider(lookup_invocation) env_conf = environment.configuration return nil if env_conf.nil? || env_conf.path_to_env.nil? # Get the name of the data provider from the environment's configuration provider_name = env_conf.environment_data_provider env_path = Pathname(env_conf.path_to_env) config_path = env_path + HieraConfig::CONFIG_FILE_NAME ep = nil if config_path.exist? ep = EnvironmentDataProvider.new # A version 5 hiera.yaml trumps any data provider setting in the environment.conf ep_config = ep.config(lookup_invocation) if ep_config.nil? ep = nil elsif ep_config.version >= 5 unless provider_name.nil? || Puppet[:strict] == :off Puppet.warn_once('deprecations', 'environment.conf#data_provider', _("Defining environment_data_provider='%{provider_name}' in environment.conf is deprecated") % { provider_name: provider_name }, env_path + 'environment.conf') unless provider_name == 'hiera' Puppet.warn_once('deprecations', 'environment.conf#data_provider_overridden', _("The environment_data_provider='%{provider_name}' setting is ignored since '%{config_path}' version >= 5") % { provider_name: provider_name, config_path: config_path }, env_path + 'environment.conf') end end provider_name = nil end end if provider_name.nil? ep else unless Puppet[:strict] == :off msg = _("Defining environment_data_provider='%{provider_name}' in environment.conf is deprecated.") % { provider_name: provider_name } msg += " " + _("A '%{hiera_config}' file should be used instead") % { hiera_config: HieraConfig::CONFIG_FILE_NAME } if ep.nil? Puppet.warn_once('deprecations', 'environment.conf#data_provider', msg, env_path + 'environment.conf') end case provider_name when 'none' nil when 'hiera' # Use hiera.yaml or default settings if it is missing ep || EnvironmentDataProvider.new when 'function' ep = EnvironmentDataProvider.new ep.config = HieraConfigV5.v4_function_config(env_path, 'environment::data', ep) ep else raise Puppet::Error, _("Environment '%{env}', cannot find environment_data_provider '%{provider}'") % { env: environment.name, provider: provider_name } end end end # @return [Puppet::Node::Environment] the environment of the compiler that this adapter is associated with def environment @compiler.environment end end end end require_relative 'invocation' require_relative 'global_data_provider' require_relative 'environment_data_provider' require_relative 'module_data_provider'
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/lookup_key.rb
lib/puppet/pops/lookup/lookup_key.rb
# frozen_string_literal: true require_relative 'sub_lookup' module Puppet::Pops module Lookup # @api private class LookupKey include SubLookup attr_reader :module_name, :root_key, :segments def initialize(key) segments = split_key(key) { |problem| Puppet::DataBinding::LookupError.new(_("%{problem} in key: '%{key}'") % { problem: problem, key: key }) } root_key = segments.shift.freeze qual_index = root_key.index(DOUBLE_COLON) @key = key @module_name = qual_index.nil? ? nil : root_key[0..qual_index - 1].freeze @root_key = root_key @segments = segments.empty? ? nil : segments.freeze end def dig(lookup_invocation, value) @segments.nil? ? value : sub_lookup(@key, lookup_invocation, @segments, value) end # Prunes a found root value with respect to subkeys in this key. The given _value_ is returned untouched # if this key has no subkeys. Otherwise an attempt is made to create a Hash or Array that contains only the # path to the appointed value and that value. # # If subkeys exists and no value is found, then this method will return `nil`, an empty `Array` or an empty `Hash` # to enable further merges to be applied. The returned type depends on the given _value_. # # @param value [Object] the value to prune # @return the possibly pruned value def prune(value) if @segments.nil? value else pruned = @segments.reduce(value) do |memo, segment| memo.is_a?(Hash) || memo.is_a?(Array) && segment.is_a?(Integer) ? memo[segment] : nil end if pruned.nil? case value when Hash EMPTY_HASH when Array EMPTY_ARRAY else nil end else undig(pruned) end end end # Create a structure that can be dug into using the subkeys of this key in order to find the # given _value_. If this key has no subkeys, the _value_ is returned. # # @param value [Object] the value to wrap in a structure in case this value has subkeys # @return [Object] the possibly wrapped value def undig(value) @segments.nil? ? value : segments.reverse.reduce(value) do |memo, segment| if segment.is_a?(Integer) x = [] x[segment] = memo else x = { segment => memo } end x end end def to_a unless instance_variable_defined?(:@all_segments) a = [@root_key] a += @segments unless @segments.nil? @all_segments = a.freeze end @all_segments end def eql?(v) v.is_a?(LookupKey) && @key == v.to_s end alias == eql? def hash @key.hash end def to_s @key end LOOKUP_OPTIONS = LookupKey.new('lookup_options') end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/environment_data_provider.rb
lib/puppet/pops/lookup/environment_data_provider.rb
# frozen_string_literal: true require_relative 'configured_data_provider' module Puppet::Pops module Lookup # @api private class EnvironmentDataProvider < ConfiguredDataProvider def place 'Environment' end protected def assert_config_version(config) if config.version > 3 config else if Puppet[:strict] == :error config.fail(Issues::HIERA_VERSION_3_NOT_GLOBAL, :where => 'environment') else Puppet.warn_once(:hiera_v3_at_env_root, config.config_path, _('hiera.yaml version 3 found at the environment root was ignored'), config.config_path) end nil end end # Return the root of the environment # # @param lookup_invocation [Invocation] The current lookup invocation # @return [Pathname] Path to root of the environment def provider_root(lookup_invocation) Pathname.new(lookup_invocation.scope.environment.configuration.path_to_env) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/hiera_config.rb
lib/puppet/pops/lookup/hiera_config.rb
# frozen_string_literal: true require_relative 'data_dig_function_provider' require_relative 'data_hash_function_provider' require_relative 'lookup_key_function_provider' require_relative 'location_resolver' module Puppet::Pops module Lookup # @api private class ScopeLookupCollectingInvocation < Invocation def initialize(scope) super(scope) @scope_interpolations = [] end def remember_scope_lookup(key, root_key, segments, value) @scope_interpolations << [key, root_key, segments, value] unless !value.nil? && key.start_with?('::') end def scope_interpolations # Save extra checks by keeping the array unique with respect to the key (first entry) @scope_interpolations.uniq! { |si| si[0] } @scope_interpolations end # Yield invocation that remembers all but the given name def with_local_memory_eluding(name) save_si = @scope_interpolations @scope_interpolations = [] result = yield save_si.concat(@scope_interpolations.reject { |entry| entry[1] == name }) @scope_interpolations = save_si result end end # @api private class HieraConfig include LocationResolver include LabelProvider CONFIG_FILE_NAME = 'hiera.yaml' KEY_NAME = 'name' KEY_VERSION = 'version' KEY_DATADIR = 'datadir' KEY_DEFAULT_HIERARCHY = 'default_hierarchy' KEY_HIERARCHY = 'hierarchy' KEY_PLAN_HIERARCHY = 'plan_hierarchy' KEY_LOGGER = 'logger' KEY_OPTIONS = 'options' KEY_PATH = 'path' KEY_PATHS = 'paths' KEY_MAPPED_PATHS = 'mapped_paths' KEY_GLOB = 'glob' KEY_GLOBS = 'globs' KEY_URI = 'uri' KEY_URIS = 'uris' KEY_DEFAULTS = 'defaults' KEY_DATA_HASH = DataHashFunctionProvider::TAG KEY_LOOKUP_KEY = LookupKeyFunctionProvider::TAG KEY_DATA_DIG = DataDigFunctionProvider::TAG KEY_V3_DATA_HASH = V3DataHashFunctionProvider::TAG KEY_V3_LOOKUP_KEY = V3LookupKeyFunctionProvider::TAG KEY_V3_BACKEND = V3BackendFunctionProvider::TAG KEY_V4_DATA_HASH = V4DataHashFunctionProvider::TAG KEY_BACKEND = 'backend' KEY_EXTENSION = 'extension' FUNCTION_KEYS = [KEY_DATA_HASH, KEY_LOOKUP_KEY, KEY_DATA_DIG, KEY_V3_BACKEND] ALL_FUNCTION_KEYS = FUNCTION_KEYS + [KEY_V4_DATA_HASH] LOCATION_KEYS = [KEY_PATH, KEY_PATHS, KEY_GLOB, KEY_GLOBS, KEY_URI, KEY_URIS, KEY_MAPPED_PATHS] FUNCTION_PROVIDERS = { KEY_DATA_HASH => DataHashFunctionProvider, KEY_DATA_DIG => DataDigFunctionProvider, KEY_LOOKUP_KEY => LookupKeyFunctionProvider, KEY_V3_DATA_HASH => V3DataHashFunctionProvider, KEY_V3_BACKEND => V3BackendFunctionProvider, KEY_V3_LOOKUP_KEY => V3LookupKeyFunctionProvider, KEY_V4_DATA_HASH => V4DataHashFunctionProvider } def self.v4_function_config(config_root, function_name, owner) unless Puppet[:strict] == :off Puppet.warn_once('deprecations', 'legacy_provider_function', _("Using of legacy data provider function '%{function_name}'. Please convert to a 'data_hash' function") % { function_name: function_name }) end HieraConfigV5.new(config_root, nil, { KEY_VERSION => 5, KEY_HIERARCHY => [ { KEY_NAME => "Legacy function '#{function_name}'", KEY_V4_DATA_HASH => function_name } ] }.freeze, owner) end def self.config_exist?(config_root) config_path = config_root + CONFIG_FILE_NAME config_path.exist? end def self.symkeys_to_string(struct) case struct when Hash map = {} struct.each_pair { |k, v| map[k.is_a?(Symbol) ? k.to_s : k] = symkeys_to_string(v) } map when Array struct.map { |v| symkeys_to_string(v) } else struct end end # Creates a new HieraConfig from the given _config_root_. This is where the 'hiera.yaml' is expected to be found # and is also the base location used when resolving relative paths. # # @param lookup_invocation [Invocation] Invocation data containing scope, overrides, and defaults # @param config_path [Pathname] Absolute path to the configuration file # @param owner [ConfiguredDataProvider] The data provider that will own the created configuration # @return [LookupConfiguration] the configuration def self.create(lookup_invocation, config_path, owner) if config_path.is_a?(Hash) config_path = nil loaded_config = config_path else config_root = config_path.parent if config_path.exist? env_context = EnvironmentContext.adapt(lookup_invocation.scope.compiler.environment) loaded_config = env_context.cached_file_data(config_path) do |content| parsed = Puppet::Util::Yaml.safe_load(content, [Symbol], config_path) # For backward compatibility, we must treat an empty file, or a yaml that doesn't # produce a Hash as Hiera version 3 default. if parsed.is_a?(Hash) parsed else Puppet.warning(_("%{config_path}: File exists but does not contain a valid YAML hash. Falling back to Hiera version 3 default config") % { config_path: config_path }) HieraConfigV3::DEFAULT_CONFIG_HASH end end else config_path = nil loaded_config = HieraConfigV5::DEFAULT_CONFIG_HASH end end version = loaded_config[KEY_VERSION] || loaded_config[:version] version = version.nil? ? 3 : version.to_i case version when 5 HieraConfigV5.new(config_root, config_path, loaded_config, owner) when 4 HieraConfigV4.new(config_root, config_path, loaded_config, owner) when 3 HieraConfigV3.new(config_root, config_path, loaded_config, owner) else issue = Issues::HIERA_UNSUPPORTED_VERSION raise Puppet::DataBinding::LookupError.new( issue.format(:version => version), config_path, nil, nil, nil, issue.issue_code ) end end attr_reader :config_path # Creates a new HieraConfig from the given _config_root_. This is where the 'lookup.yaml' is expected to be found # and is also the base location used when resolving relative paths. # # @param config_path [Pathname] Absolute path to the configuration # @param loaded_config [Hash] the loaded configuration def initialize(config_root, config_path, loaded_config, owner) @config_root = config_root @config_path = config_path @loaded_config = loaded_config @config = validate_config(self.class.symkeys_to_string(@loaded_config), owner) @data_providers = nil end def fail(issue, args = EMPTY_HASH, line = nil) raise Puppet::DataBinding::LookupError.new( issue.format(args.merge(:label => self)), @config_path, line, nil, nil, issue.issue_code ) end def has_default_hierarchy? false end # Returns the data providers for this config # # @param lookup_invocation [Invocation] Invocation data containing scope, overrides, and defaults # @param parent_data_provider [DataProvider] The data provider that loaded this configuration # @return [Array<DataProvider>] the data providers def configured_data_providers(lookup_invocation, parent_data_provider, use_default_hierarchy = false) unless @data_providers && scope_interpolations_stable?(lookup_invocation) if @data_providers lookup_invocation.report_text { _('Hiera configuration recreated due to change of scope variables used in interpolation expressions') } end slc_invocation = ScopeLookupCollectingInvocation.new(lookup_invocation.scope) begin @data_providers = create_configured_data_providers(slc_invocation, parent_data_provider, false) if has_default_hierarchy? @default_data_providers = create_configured_data_providers(slc_invocation, parent_data_provider, true) end rescue StandardError => e # Raise a LookupError with a RUNTIME_ERROR issue to prevent this being translated to an evaluation error triggered in the pp file # where the lookup started if e.message =~ /^Undefined variable '([^']+)'/ var = ::Regexp.last_match(1) fail(Issues::HIERA_UNDEFINED_VARIABLE, { :name => var }, find_line_matching(/%\{['"]?#{var}['"]?}/)) end raise e end @scope_interpolations = slc_invocation.scope_interpolations end use_default_hierarchy ? @default_data_providers : @data_providers end # Find first line in configuration that matches regexp after given line. Comments are stripped def find_line_matching(regexp, start_line = 1) line_number = 0 File.foreach(@config_path) do |line| line_number += 1 next if line_number < start_line quote = nil stripped = ''.dup line.each_codepoint do |cp| case cp when 0x22, 0x27 # double or single quote if quote == cp quote = nil elsif quote.nil? quote = cp end when 0x23 # unquoted hash mark break end stripped << cp end return line_number if stripped =~ regexp end nil end def scope_interpolations_stable?(lookup_invocation) if @scope_interpolations.empty? true else scope = lookup_invocation.scope lookup_invocation.without_explain do @scope_interpolations.all? do |key, root_key, segments, old_value| value = Puppet.override(avoid_hiera_interpolation_errors: true) { scope[root_key] } unless value.nil? || segments.empty? found = nil; catch(:no_such_key) { found = sub_lookup(key, lookup_invocation, segments, value) } value = found; end old_value.eql?(value) end end end end # @api private def create_configured_data_providers(lookup_invocation, parent_data_provider, use_default_hierarchy) self.class.not_implemented(self, 'create_configured_data_providers') end def validate_config(config, owner) self.class.not_implemented(self, 'validate_config') end def version self.class.not_implemented(self, 'version') end def name "hiera configuration version #{version}" end def create_hiera3_backend_provider(name, backend, parent_data_provider, datadir, paths, hiera3_config) # Custom backend. Hiera 3 must be installed, its logger configured, and it must be made aware of the loaded config raise Puppet::DataBinding::LookupError, 'Hiera 3 is not installed' unless Puppet.features.hiera? if Hiera::Config.instance_variable_defined?(:@config) && (current_config = Hiera::Config.instance_variable_get(:@config)).is_a?(Hash) current_config.each_pair do |key, val| case key when :hierarchy, :backends hiera3_config[key] = ([val] + [hiera3_config[key]]).flatten.uniq else hiera3_config[key] = val end end elsif hiera3_config.include?(KEY_LOGGER) Hiera.logger = hiera3_config[KEY_LOGGER].to_s else Hiera.logger = 'puppet' end unless Hiera::Interpolate.const_defined?(:PATCHED_BY_HIERA_5) # Replace the class methods 'hiera_interpolate' and 'alias_interpolate' with a method that wires back and performs global # lookups using the lookup framework. This is necessary since the classic Hiera is made aware only of custom backends. class << Hiera::Interpolate hiera_interpolate = proc do |_data, key, scope, _extra_data, context| override = context[:order_override] invocation = Puppet::Pops::Lookup::Invocation.current unless override.nil? && invocation.global_only? invocation = Puppet::Pops::Lookup::Invocation.new(scope) invocation.set_global_only invocation.set_hiera_v3_location_overrides(override) unless override.nil? end Puppet::Pops::Lookup::LookupAdapter.adapt(scope.compiler).lookup(key, invocation, nil) end send(:remove_method, :hiera_interpolate) send(:remove_method, :alias_interpolate) send(:define_method, :hiera_interpolate, hiera_interpolate) send(:define_method, :alias_interpolate, hiera_interpolate) end Hiera::Interpolate.send(:const_set, :PATCHED_BY_HIERA_5, true) end Hiera::Config.instance_variable_set(:@config, hiera3_config) # Use a special lookup_key that delegates to the backend paths = nil if !paths.nil? && paths.empty? create_data_provider(name, parent_data_provider, KEY_V3_BACKEND, 'hiera_v3_data', { KEY_DATADIR => datadir, KEY_BACKEND => backend }, paths) end private def create_data_provider(name, parent_data_provider, function_kind, function_name, options, locations) FUNCTION_PROVIDERS[function_kind].new(name, parent_data_provider, function_name, options, locations) end def self.not_implemented(impl, method_name) raise NotImplementedError, "The class #{impl.class.name} should have implemented the method #{method_name}()" end private_class_method :not_implemented end # @api private class HieraConfigV3 < HieraConfig KEY_BACKENDS = 'backends' KEY_MERGE_BEHAVIOR = 'merge_behavior' KEY_DEEP_MERGE_OPTIONS = 'deep_merge_options' def self.config_type return @@CONFIG_TYPE if class_variable_defined?(:@@CONFIG_TYPE) tf = Types::TypeFactory nes_t = Types::PStringType::NON_EMPTY # This is a hash, not a type. Contained backends are added prior to validation @@CONFIG_TYPE = { tf.optional(KEY_VERSION) => tf.range(3, 3), tf.optional(KEY_BACKENDS) => tf.variant(nes_t, tf.array_of(nes_t)), tf.optional(KEY_LOGGER) => nes_t, tf.optional(KEY_MERGE_BEHAVIOR) => tf.enum('deep', 'deeper', 'native'), tf.optional(KEY_DEEP_MERGE_OPTIONS) => tf.hash_kv(nes_t, tf.variant(tf.string, tf.boolean)), tf.optional(KEY_HIERARCHY) => tf.variant(nes_t, tf.array_of(nes_t)) } end def create_configured_data_providers(lookup_invocation, parent_data_provider, _) scope = lookup_invocation.scope unless scope.is_a?(Hiera::Scope) lookup_invocation = Invocation.new( Hiera::Scope.new(scope), lookup_invocation.override_values, lookup_invocation.default_values, lookup_invocation.explainer ) end default_datadir = File.join(Puppet.settings[:codedir], 'environments', '%{::environment}', 'hieradata') data_providers = {} [@config[KEY_BACKENDS]].flatten.each do |backend| if data_providers.include?(backend) first_line = find_line_matching(/[^\w]#{backend}(?:[^\w]|$)/) line = find_line_matching(/[^\w]#{backend}(?:[^\w]|$)/, first_line + 1) if first_line unless line line = first_line first_line = nil end fail(Issues::HIERA_BACKEND_MULTIPLY_DEFINED, { :name => backend, :first_line => first_line }, line) end original_paths = [@config[KEY_HIERARCHY]].flatten backend_config = @config[backend] if backend_config.nil? backend_config = EMPTY_HASH else backend_config = interpolate(backend_config, lookup_invocation, false) end datadir = Pathname(backend_config[KEY_DATADIR] || interpolate(default_datadir, lookup_invocation, false)) ext = backend_config[KEY_EXTENSION] if ext.nil? ext = backend == 'hocon' ? '.conf' : ".#{backend}" else ext = ".#{ext}" end paths = resolve_paths(datadir, original_paths, lookup_invocation, @config_path.nil?, ext) data_providers[backend] = if %w[json yaml].include? backend create_data_provider(backend, parent_data_provider, KEY_V3_DATA_HASH, "#{backend}_data", { KEY_DATADIR => datadir }, paths) elsif backend == 'hocon' && Puppet.features.hocon? create_data_provider(backend, parent_data_provider, KEY_V3_DATA_HASH, 'hocon_data', { KEY_DATADIR => datadir }, paths) elsif backend == 'eyaml' && Puppet.features.hiera_eyaml? create_data_provider(backend, parent_data_provider, KEY_V3_LOOKUP_KEY, 'eyaml_lookup_key', backend_config.merge(KEY_DATADIR => datadir), paths) else create_hiera3_backend_provider(backend, backend, parent_data_provider, datadir, paths, @loaded_config) end end data_providers.values end DEFAULT_CONFIG_HASH = { KEY_BACKENDS => %w[yaml], KEY_HIERARCHY => %w[nodes/%{::trusted.certname} common], KEY_MERGE_BEHAVIOR => 'native' } def validate_config(config, owner) unless Puppet[:strict] == :off Puppet.warn_once('deprecations', 'hiera.yaml', _("%{config_path}: Use of 'hiera.yaml' version 3 is deprecated. It should be converted to version 5") % { config_path: @config_path }, config_path.to_s) end config[KEY_VERSION] ||= 3 config[KEY_BACKENDS] ||= DEFAULT_CONFIG_HASH[KEY_BACKENDS] config[KEY_HIERARCHY] ||= DEFAULT_CONFIG_HASH[KEY_HIERARCHY] config[KEY_MERGE_BEHAVIOR] ||= DEFAULT_CONFIG_HASH[KEY_MERGE_BEHAVIOR] config[KEY_DEEP_MERGE_OPTIONS] ||= {} backends = [config[KEY_BACKENDS]].flatten # Create the final struct used for validation (backends are included as keys to arbitrary configs in the form of a hash) tf = Types::TypeFactory backend_elements = {} backends.each { |backend| backend_elements[tf.optional(backend)] = tf.hash_kv(Types::PStringType::NON_EMPTY, tf.any) } v3_struct = tf.struct(self.class.config_type.merge(backend_elements)) Types::TypeAsserter.assert_instance_of(["The Lookup Configuration at '%s'", @config_path], v3_struct, config) end def merge_strategy @merge_strategy ||= create_merge_strategy end def version 3 end private def create_merge_strategy key = @config[KEY_MERGE_BEHAVIOR] case key when nil, 'native' MergeStrategy.strategy(nil) when 'array' MergeStrategy.strategy(:unique) when 'deep', 'deeper' merge = { 'strategy' => key == 'deep' ? 'reverse_deep' : 'unconstrained_deep' } dm_options = @config[KEY_DEEP_MERGE_OPTIONS] merge.merge!(dm_options) if dm_options MergeStrategy.strategy(merge) end end end # @api private class HieraConfigV4 < HieraConfig def self.config_type return @@CONFIG_TYPE if class_variable_defined?(:@@CONFIG_TYPE) tf = Types::TypeFactory nes_t = Types::PStringType::NON_EMPTY @@CONFIG_TYPE = tf.struct({ KEY_VERSION => tf.range(4, 4), tf.optional(KEY_DATADIR) => nes_t, tf.optional(KEY_HIERARCHY) => tf.array_of(tf.struct( KEY_BACKEND => nes_t, KEY_NAME => nes_t, tf.optional(KEY_DATADIR) => nes_t, tf.optional(KEY_PATH) => nes_t, tf.optional(KEY_PATHS) => tf.array_of(nes_t) )) }) end def create_configured_data_providers(lookup_invocation, parent_data_provider, _) default_datadir = @config[KEY_DATADIR] data_providers = {} @config[KEY_HIERARCHY].each do |he| name = he[KEY_NAME] if data_providers.include?(name) first_line = find_line_matching(/\s+name:\s+['"]?#{name}(?:[^\w]|$)/) line = find_line_matching(/\s+name:\s+['"]?#{name}(?:[^\w]|$)/, first_line + 1) if first_line unless line line = first_line first_line = nil end fail(Issues::HIERA_HIERARCHY_NAME_MULTIPLY_DEFINED, { :name => name, :first_line => first_line }, line) end original_paths = he[KEY_PATHS] || [he[KEY_PATH] || name] datadir = @config_root + (he[KEY_DATADIR] || default_datadir) provider_name = he[KEY_BACKEND] data_providers[name] = if %w[json yaml].include?(provider_name) create_data_provider(name, parent_data_provider, KEY_DATA_HASH, "#{provider_name}_data", {}, resolve_paths(datadir, original_paths, lookup_invocation, @config_path.nil?, ".#{provider_name}")) elsif provider_name == 'hocon' && Puppet.features.hocon? create_data_provider(name, parent_data_provider, KEY_DATA_HASH, 'hocon_data', {}, resolve_paths(datadir, original_paths, lookup_invocation, @config_path.nil?, '.conf')) else fail(Issues::HIERA_NO_PROVIDER_FOR_BACKEND, { :name => provider_name }, find_line_matching(/[^\w]#{provider_name}(?:[^\w]|$)/)) end end data_providers.values end def validate_config(config, owner) unless Puppet[:strict] == :off Puppet.warn_once('deprecations', 'hiera.yaml', _("%{config_path}: Use of 'hiera.yaml' version 4 is deprecated. It should be converted to version 5") % { config_path: @config_path }, config_path.to_s) end config[KEY_DATADIR] ||= 'data' config[KEY_HIERARCHY] ||= [{ KEY_NAME => 'common', KEY_BACKEND => 'yaml' }] Types::TypeAsserter.assert_instance_of(["The Lookup Configuration at '%s'", @config_path], self.class.config_type, config) end def version 4 end end # @api private class HieraConfigV5 < HieraConfig def self.config_type return @@CONFIG_TYPE if class_variable_defined?(:@@CONFIG_TYPE_V5) tf = Types::TypeFactory nes_t = Types::PStringType::NON_EMPTY # Validated using Ruby URI implementation uri_t = Types::PStringType::NON_EMPTY # The option name must start with a letter and end with a letter or digit. May contain underscore and dash. option_name_t = tf.pattern(/\A[A-Za-z](:?[0-9A-Za-z_-]*[0-9A-Za-z])?\z/) hierarchy_t = tf.array_of(tf.struct( { KEY_NAME => nes_t, tf.optional(KEY_OPTIONS) => tf.hash_kv(option_name_t, tf.data), tf.optional(KEY_DATA_HASH) => nes_t, tf.optional(KEY_LOOKUP_KEY) => nes_t, tf.optional(KEY_V3_BACKEND) => nes_t, tf.optional(KEY_V4_DATA_HASH) => nes_t, tf.optional(KEY_DATA_DIG) => nes_t, tf.optional(KEY_PATH) => nes_t, tf.optional(KEY_PATHS) => tf.array_of(nes_t, tf.range(1, :default)), tf.optional(KEY_GLOB) => nes_t, tf.optional(KEY_GLOBS) => tf.array_of(nes_t, tf.range(1, :default)), tf.optional(KEY_URI) => uri_t, tf.optional(KEY_URIS) => tf.array_of(uri_t, tf.range(1, :default)), tf.optional(KEY_MAPPED_PATHS) => tf.array_of(nes_t, tf.range(3, 3)), tf.optional(KEY_DATADIR) => nes_t } )) @@CONFIG_TYPE = tf.struct({ KEY_VERSION => tf.range(5, 5), tf.optional(KEY_DEFAULTS) => tf.struct( { tf.optional(KEY_DATA_HASH) => nes_t, tf.optional(KEY_LOOKUP_KEY) => nes_t, tf.optional(KEY_DATA_DIG) => nes_t, tf.optional(KEY_DATADIR) => nes_t, tf.optional(KEY_OPTIONS) => tf.hash_kv(option_name_t, tf.data), } ), tf.optional(KEY_HIERARCHY) => hierarchy_t, tf.optional(KEY_PLAN_HIERARCHY) => hierarchy_t, tf.optional(KEY_DEFAULT_HIERARCHY) => hierarchy_t }) end def create_configured_data_providers(lookup_invocation, parent_data_provider, use_default_hierarchy) defaults = @config[KEY_DEFAULTS] || EMPTY_HASH datadir = defaults[KEY_DATADIR] || 'data' # Hashes enumerate their values in the order that the corresponding keys were inserted so it's safe to use # a hash for the data_providers. data_providers = {} if @config.include?(KEY_DEFAULT_HIERARCHY) unless parent_data_provider.is_a?(ModuleDataProvider) fail(Issues::HIERA_DEFAULT_HIERARCHY_NOT_IN_MODULE, EMPTY_HASH, find_line_matching(/\s+default_hierarchy:/)) end elsif use_default_hierarchy return data_providers end compiler = Puppet.lookup(:pal_compiler) { nil } config_key = if compiler.is_a?(Puppet::Pal::ScriptCompiler) && !@config[KEY_PLAN_HIERARCHY].nil? KEY_PLAN_HIERARCHY elsif use_default_hierarchy KEY_DEFAULT_HIERARCHY else KEY_HIERARCHY end @config[config_key].each do |he| name = he[KEY_NAME] if data_providers.include?(name) first_line = find_line_matching(/\s+name:\s+['"]?#{name}(?:[^\w]|$)/) line = find_line_matching(/\s+name:\s+['"]?#{name}(?:[^\w]|$)/, first_line + 1) if first_line unless line line = first_line first_line = nil end fail(Issues::HIERA_HIERARCHY_NAME_MULTIPLY_DEFINED, { :name => name, :first_line => first_line }, line) end function_kind = ALL_FUNCTION_KEYS.find { |key| he.include?(key) } if function_kind.nil? function_kind = FUNCTION_KEYS.find { |key| defaults.include?(key) } function_name = defaults[function_kind] else function_name = he[function_kind] end entry_datadir = @config_root + (he[KEY_DATADIR] || datadir) entry_datadir = Pathname(interpolate(entry_datadir.to_s, lookup_invocation, false)) location_key = LOCATION_KEYS.find { |key| he.include?(key) } locations = [] Puppet.override(avoid_hiera_interpolation_errors: true) do locations = case location_key when KEY_PATHS resolve_paths(entry_datadir, he[location_key], lookup_invocation, @config_path.nil?) when KEY_PATH resolve_paths(entry_datadir, [he[location_key]], lookup_invocation, @config_path.nil?) when KEY_GLOBS expand_globs(entry_datadir, he[location_key], lookup_invocation) when KEY_GLOB expand_globs(entry_datadir, [he[location_key]], lookup_invocation) when KEY_URIS expand_uris(he[location_key], lookup_invocation) when KEY_URI expand_uris([he[location_key]], lookup_invocation) when KEY_MAPPED_PATHS expand_mapped_paths(entry_datadir, he[location_key], lookup_invocation) else nil end end next if @config_path.nil? && !locations.nil? && locations.empty? # Default config and no existing paths found options = he[KEY_OPTIONS] || defaults[KEY_OPTIONS] options = options.nil? ? EMPTY_HASH : interpolate(options, lookup_invocation, false) if function_kind == KEY_V3_BACKEND v3options = { :datadir => entry_datadir.to_s } options.each_pair { |k, v| v3options[k.to_sym] = v } data_providers[name] = create_hiera3_backend_provider(name, function_name, parent_data_provider, entry_datadir, locations, { :hierarchy => if locations.nil? [] else locations.map do |loc| path = loc.original_location path.end_with?(".#{function_name}") ? path[0..-(function_name.length + 2)] : path end end, function_name.to_sym => v3options, :backends => [function_name], :logger => 'puppet' }) else data_providers[name] = create_data_provider(name, parent_data_provider, function_kind, function_name, options, locations) end end data_providers.values end def has_default_hierarchy? @config.include?(KEY_DEFAULT_HIERARCHY) end RESERVED_OPTION_KEYS = %w[path uri].freeze DEFAULT_CONFIG_HASH = { KEY_VERSION => 5, KEY_DEFAULTS => { KEY_DATADIR => 'data', KEY_DATA_HASH => 'yaml_data' }, KEY_HIERARCHY => [ { KEY_NAME => 'Common', KEY_PATH => 'common.yaml', } ] }.freeze def validate_config(config, owner) config[KEY_DEFAULTS] ||= DEFAULT_CONFIG_HASH[KEY_DEFAULTS] config[KEY_HIERARCHY] ||= DEFAULT_CONFIG_HASH[KEY_HIERARCHY] Types::TypeAsserter.assert_instance_of(["The Lookup Configuration at '%s'", @config_path], self.class.config_type, config) defaults = config[KEY_DEFAULTS] validate_defaults(defaults) unless defaults.nil? config[KEY_HIERARCHY].each { |he| validate_hierarchy(he, defaults, owner) } if config.include?(KEY_PLAN_HIERARCHY) config[KEY_PLAN_HIERARCHY].each { |he| validate_hierarchy(he, defaults, owner) } end if config.include?(KEY_DEFAULT_HIERARCHY) unless owner.is_a?(ModuleDataProvider) fail(Issues::HIERA_DEFAULT_HIERARCHY_NOT_IN_MODULE, EMPTY_HASH, find_line_matching(/(?:^|\s+)#{KEY_DEFAULT_HIERARCHY}:/)) end config[KEY_DEFAULT_HIERARCHY].each { |he| validate_hierarchy(he, defaults, owner) } end config end def validate_hierarchy(he, defaults, owner) name = he[KEY_NAME] case ALL_FUNCTION_KEYS.count { |key| he.include?(key) } when 0 if defaults.nil? || FUNCTION_KEYS.count { |key| defaults.include?(key) } == 0 fail(Issues::HIERA_MISSING_DATA_PROVIDER_FUNCTION, :name => name) end when 1 # OK else fail(Issues::HIERA_MULTIPLE_DATA_PROVIDER_FUNCTIONS, :name => name) end v3_backend = he[KEY_V3_BACKEND] unless v3_backend.nil? unless owner.is_a?(GlobalDataProvider) fail(Issues::HIERA_V3_BACKEND_NOT_GLOBAL, EMPTY_HASH, find_line_matching(/\s+#{KEY_V3_BACKEND}:/)) end if v3_backend == 'json' || v3_backend == 'yaml' || v3_backend == 'hocon' && Puppet.features.hocon? # Disallow use of backends that have corresponding "data_hash" functions in version 5 fail(Issues::HIERA_V3_BACKEND_REPLACED_BY_DATA_HASH, { :function_name => v3_backend }, find_line_matching(/\s+#{KEY_V3_BACKEND}:\s*['"]?#{v3_backend}(?:[^\w]|$)/)) end end if LOCATION_KEYS.count { |key| he.include?(key) } > 1 fail(Issues::HIERA_MULTIPLE_LOCATION_SPECS, :name => name) end options = he[KEY_OPTIONS] unless options.nil? RESERVED_OPTION_KEYS.each do |key| fail(Issues::HIERA_OPTION_RESERVED_BY_PUPPET, :key => key, :name => name) if options.include?(key) end end end def validate_defaults(defaults) case FUNCTION_KEYS.count { |key| defaults.include?(key) } when 0, 1 # OK else fail(Issues::HIERA_MULTIPLE_DATA_PROVIDER_FUNCTIONS_IN_DEFAULT) end options = defaults[KEY_OPTIONS] unless options.nil? RESERVED_OPTION_KEYS.each do |key| fail(Issues::HIERA_DEFAULT_OPTION_RESERVED_BY_PUPPET, :key => key) if options.include?(key) end end end def version 5 end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/key_recorder.rb
lib/puppet/pops/lookup/key_recorder.rb
# frozen_string_literal: true # This class defines the private API of the Lookup Key Recorder support. # @api private # class Puppet::Pops::Lookup::KeyRecorder def initialize end # rubocop:disable Naming/MemoizedInstanceVariableName def self.singleton @null_recorder ||= new end # rubocop:enable Naming/MemoizedInstanceVariableName # Records a key # (This implementation does nothing) # def record(key) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/sub_lookup.rb
lib/puppet/pops/lookup/sub_lookup.rb
# frozen_string_literal: true module Puppet::Pops module Lookup module SubLookup SPECIAL = /['".]/ # Split key into segments. A segment may be a quoted string (both single and double quotes can # be used) and the segment separator is the '.' character. Whitespace will be trimmed off on # both sides of each segment. Whitespace within quotes are not trimmed. # # If the key cannot be parsed, this method will yield a string describing the problem to a one # parameter block. The block must return an exception instance. # # @param key [String] the string to split # @return [Array<String>] the array of segments # @yieldparam problem [String] the problem, i.e. 'Syntax error' # @yieldreturn [Exception] the exception to raise # # @api public def split_key(key) return [key] if key.match(SPECIAL).nil? segments = key.split(/(\s*"[^"]+"\s*|\s*'[^']+'\s*|[^'".]+)/) if segments.empty? # Only happens if the original key was an empty string raise yield('Syntax error') elsif segments.shift == '' count = segments.size raise yield('Syntax error') unless count > 0 segments.keep_if { |seg| seg != '.' } raise yield('Syntax error') unless segments.size * 2 == count + 1 segments.map! do |segment| segment.strip! if segment.start_with?('"', "'") segment[1..-2] elsif segment =~ /^(:?[+-]?[0-9]+)$/ segment.to_i else segment end end else raise yield('Syntax error') end end # Perform a sub-lookup using the given _segments_ to access the given _value_. Each segment must be a string. A string # consisting entirely of digits will be treated as an indexed lookup which means that the value that it is applied to # must be an array. Other types of segments will expect that the given value is something other than a String that # implements the '#[]' method. # # @param key [String] the original key (only used for error messages) # @param context [Context] The current lookup context # @param segments [Array<String>] the segments to use for lookup # @param value [Object] the value to access using the segments # @return [Object] the value obtained when accessing the value # # @api public def sub_lookup(key, context, segments, value) lookup_invocation = context.is_a?(Invocation) ? context : context.invocation lookup_invocation.with(:sub_lookup, segments) do segments.each do |segment| lookup_invocation.with(:segment, segment) do if value.nil? lookup_invocation.report_not_found(segment) throw :no_such_key end if segment.is_a?(Integer) && value.instance_of?(Array) unless segment >= 0 && segment < value.size lookup_invocation.report_not_found(segment) throw :no_such_key end else unless value.respond_to?(:'[]') && !(value.is_a?(Array) || value.instance_of?(String)) raise Puppet::DataBinding::LookupError, _("Data Provider type mismatch: Got %{klass} when a hash-like object was expected to access value using '%{segment}' from key '%{key}'") % { klass: value.class.name, segment: segment, key: key } end unless value.include?(segment) lookup_invocation.report_not_found(segment) throw :no_such_key end end value = value[segment] lookup_invocation.report_found(segment, value) end end value end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/explainer.rb
lib/puppet/pops/lookup/explainer.rb
# frozen_string_literal: true module Puppet::Pops module Lookup # The ExplainNode contains information of a specific node in a tree traversed during # lookup. The tree can be traversed using the `parent` and `branches` attributes of # each node. # # Each leaf node contains information about what happened when the leaf of the branch # was traversed. class ExplainNode def branches @branches ||= [] end def to_hash hash = {} hash[:branches] = @branches.map(&:to_hash) unless @branches.nil? || @branches.empty? hash end def explain io = ''.dup dump_on(io, '', '') io end def inspect to_s end def to_s s = self.class.name s = "#{s} with #{@branches.size} branches" unless @branches.nil? s end def text(text) @texts ||= [] @texts << text end def dump_on(io, indent, first_indent) dump_texts(io, indent) end def dump_texts(io, indent) @texts.each { |text| io << indent << text << "\n" } if instance_variable_defined?(:@texts) end end class ExplainTreeNode < ExplainNode attr_reader :parent, :event, :value attr_accessor :key def initialize(parent) @parent = parent @event = nil end def found_in_overrides(key, value) @key = key.to_s @value = value @event = :found_in_overrides end def found_in_defaults(key, value) @key = key.to_s @value = value @event = :found_in_defaults end def found(key, value) @key = key.to_s @value = value @event = :found end def result(value) @value = value @event = :result end def not_found(key) @key = key.to_s @event = :not_found end def location_not_found @event = :location_not_found end def increase_indent(indent) indent + ' ' end def to_hash hash = super hash[:key] = @key unless @key.nil? hash[:value] = @value if [:found, :found_in_defaults, :found_in_overrides, :result].include?(@event) hash[:event] = @event unless @event.nil? hash[:texts] = @texts unless @texts.nil? hash[:type] = type hash end def type :root end def dump_outcome(io, indent) case @event when :not_found io << indent << 'No such key: "' << @key << "\"\n" when :found, :found_in_overrides, :found_in_defaults io << indent << 'Found key: "' << @key << '" value: ' dump_value(io, indent, @value) io << ' in overrides' if @event == :found_in_overrides io << ' in defaults' if @event == :found_in_defaults io << "\n" end dump_texts(io, indent) end def dump_value(io, indent, value) case value when Hash io << '{' unless value.empty? inner_indent = increase_indent(indent) value.reduce("\n") do |sep, (k, v)| io << sep << inner_indent dump_value(io, inner_indent, k) io << ' => ' dump_value(io, inner_indent, v) ",\n" end io << "\n" << indent end io << '}' when Array io << '[' unless value.empty? inner_indent = increase_indent(indent) value.reduce("\n") do |sep, v| io << sep << inner_indent dump_value(io, inner_indent, v) ",\n" end io << "\n" << indent end io << ']' else io << value.inspect end end def to_s "#{self.class.name}: #{@key}, #{@event}" end end class ExplainTop < ExplainTreeNode def initialize(parent, type, key) super(parent) @type = type self.key = key.to_s end def dump_on(io, indent, first_indent) io << first_indent << 'Searching for "' << key << "\"\n" indent = increase_indent(indent) branches.each { |b| b.dump_on(io, indent, indent) } end end class ExplainInvalidKey < ExplainTreeNode def initialize(parent, key) super(parent) @key = key.to_s end def dump_on(io, indent, first_indent) io << first_indent << "Invalid key \"" << @key << "\"\n" end def type :invalid_key end end class ExplainMergeSource < ExplainNode attr_reader :merge_source def initialize(merge_source) @merge_source = merge_source end def dump_on(io, indent, first_indent) io << first_indent << 'Using merge options from "' << merge_source << "\" hash\n" end def to_hash { :type => type, :merge_source => merge_source } end def type :merge_source end end class ExplainModule < ExplainTreeNode def initialize(parent, module_name) super(parent) @module_name = module_name end def dump_on(io, indent, first_indent) case @event when :module_not_found io << indent << 'Module "' << @module_name << "\" not found\n" when :module_provider_not_found io << indent << 'Module data provider for module "' << @module_name << "\" not found\n" end end def module_not_found @event = :module_not_found end def module_provider_not_found @event = :module_provider_not_found end def type :module end end class ExplainInterpolate < ExplainTreeNode def initialize(parent, expression) super(parent) @expression = expression end def dump_on(io, indent, first_indent) io << first_indent << 'Interpolation on "' << @expression << "\"\n" indent = increase_indent(indent) branches.each { |b| b.dump_on(io, indent, indent) } end def to_hash hash = super hash[:expression] = @expression hash end def type :interpolate end end class ExplainMerge < ExplainTreeNode def initialize(parent, merge) super(parent) @merge = merge end def dump_on(io, indent, first_indent) return if branches.size == 0 # It's pointless to report a merge where there's only one branch return branches[0].dump_on(io, indent, first_indent) if branches.size == 1 io << first_indent << 'Merge strategy ' << @merge.class.key.to_s << "\n" indent = increase_indent(indent) options = options_wo_strategy unless options.nil? io << indent << 'Options: ' dump_value(io, indent, options) io << "\n" end branches.each { |b| b.dump_on(io, indent, indent) } if @event == :result io << indent << 'Merged result: ' dump_value(io, indent, @value) io << "\n" end end def to_hash return branches[0].to_hash if branches.size == 1 hash = super hash[:merge] = @merge.class.key options = options_wo_strategy hash[:options] = options unless options.nil? hash end def type :merge end def options_wo_strategy options = @merge.options if !options.nil? && options.include?('strategy') options = options.dup options.delete('strategy') end options.empty? ? nil : options end end class ExplainGlobal < ExplainTreeNode def initialize(parent, binding_terminus) super(parent) @binding_terminus = binding_terminus end def dump_on(io, indent, first_indent) io << first_indent << 'Data Binding "' << @binding_terminus.to_s << "\"\n" indent = increase_indent(indent) branches.each { |b| b.dump_on(io, indent, indent) } dump_outcome(io, indent) end def to_hash hash = super hash[:name] = @binding_terminus hash end def type :global end end class ExplainDataProvider < ExplainTreeNode def initialize(parent, provider) super(parent) @provider = provider end def dump_on(io, indent, first_indent) io << first_indent << @provider.name << "\n" indent = increase_indent(indent) if @provider.respond_to?(:config_path) path = @provider.config_path io << indent << 'Using configuration "' << path.to_s << "\"\n" unless path.nil? end branches.each { |b| b.dump_on(io, indent, indent) } dump_outcome(io, indent) end def to_hash hash = super hash[:name] = @provider.name if @provider.respond_to?(:config_path) path = @provider.config_path hash[:configuration_path] = path.to_s unless path.nil? end hash[:module] = @provider.module_name if @provider.is_a?(ModuleDataProvider) hash end def type :data_provider end end class ExplainLocation < ExplainTreeNode def initialize(parent, location) super(parent) @location = location end def dump_on(io, indent, first_indent) location = @location.location type_name = type == :path ? 'Path' : 'URI' io << indent << type_name << ' "' << location.to_s << "\"\n" indent = increase_indent(indent) io << indent << 'Original ' << type_name.downcase << ': "' << @location.original_location << "\"\n" branches.each { |b| b.dump_on(io, indent, indent) } io << indent << type_name << " not found\n" if @event == :location_not_found dump_outcome(io, indent) end def to_hash hash = super location = @location.location if type == :path hash[:original_path] = @location.original_location hash[:path] = location.to_s else hash[:original_uri] = @location.original_location hash[:uri] = location.to_s end hash end def type @location.location.is_a?(Pathname) ? :path : :uri end end class ExplainSubLookup < ExplainTreeNode def initialize(parent, sub_key) super(parent) @sub_key = sub_key end def dump_on(io, indent, first_indent) io << indent << 'Sub key: "' << @sub_key.join('.') << "\"\n" indent = increase_indent(indent) branches.each { |b| b.dump_on(io, indent, indent) } dump_outcome(io, indent) end def type :sub_key end end class ExplainKeySegment < ExplainTreeNode def initialize(parent, segment) super(parent) @segment = segment end def dump_on(io, indent, first_indent) dump_outcome(io, indent) end def type :segment end end class ExplainScope < ExplainTreeNode def initialize(parent, name) super(parent) @name = name end def dump_on(io, indent, first_indent) io << indent << @name << "\n" indent = increase_indent(indent) branches.each { |b| b.dump_on(io, indent, indent) } dump_outcome(io, indent) end def to_hash hash = super hash[:name] = @name hash end def type :scope end end class Explainer < ExplainNode def initialize(explain_options = false, only_explain_options = false) @current = self @explain_options = explain_options @only_explain_options = only_explain_options end def push(qualifier_type, qualifier) node = case qualifier_type when :global ExplainGlobal.new(@current, qualifier) when :location ExplainLocation.new(@current, qualifier) when :interpolate ExplainInterpolate.new(@current, qualifier) when :data_provider ExplainDataProvider.new(@current, qualifier) when :merge ExplainMerge.new(@current, qualifier) when :module ExplainModule.new(@current, qualifier) when :scope ExplainScope.new(@current, qualifier) when :sub_lookup ExplainSubLookup.new(@current, qualifier) when :segment ExplainKeySegment.new(@current, qualifier) when :meta, :data ExplainTop.new(@current, qualifier_type, qualifier) when :invalid_key ExplainInvalidKey.new(@current, qualifier) else # TRANSLATORS 'Explain' is referring to the 'Explainer' class and should not be translated raise ArgumentError, _("Unknown Explain type %{qualifier_type}") % { qualifier_type: qualifier_type } end @current.branches << node @current = node end def only_explain_options? @only_explain_options end def explain_options? @explain_options end def pop @current = @current.parent unless @current.parent.nil? end def accept_found_in_overrides(key, value) @current.found_in_overrides(key, value) end def accept_found_in_defaults(key, value) @current.found_in_defaults(key, value) end def accept_found(key, value) @current.found(key, value) end def accept_merge_source(merge_source) @current.branches << ExplainMergeSource.new(merge_source) end def accept_not_found(key) @current.not_found(key) end def accept_location_not_found @current.location_not_found end def accept_module_not_found(module_name) push(:module, module_name) @current.module_not_found pop end def accept_module_provider_not_found(module_name) push(:module, module_name) @current.module_provider_not_found pop end def accept_result(result) @current.result(result) end def accept_text(text) @current.text(text) end def dump_on(io, indent, first_indent) branches.each { |b| b.dump_on(io, indent, first_indent) } dump_texts(io, indent) end def to_hash branches.size == 1 ? branches[0].to_hash : super end end class DebugExplainer < Explainer attr_reader :wrapped_explainer def initialize(wrapped_explainer) @wrapped_explainer = wrapped_explainer if wrapped_explainer.nil? @current = self @explain_options = false @only_explain_options = false else @current = wrapped_explainer @explain_options = wrapped_explainer.explain_options? @only_explain_options = wrapped_explainer.only_explain_options? end end def dump_on(io, indent, first_indent) @current.equal?(self) ? super : @current.dump_on(io, indent, first_indent) end def emit_debug_info(preamble) io = String.new io << preamble << "\n" dump_on(io, ' ', ' ') Puppet.debug(io.chomp!) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/data_hash_function_provider.rb
lib/puppet/pops/lookup/data_hash_function_provider.rb
# frozen_string_literal: true require_relative 'function_provider' require_relative 'interpolation' module Puppet::Pops module Lookup # @api private class DataHashFunctionProvider < FunctionProvider include SubLookup include Interpolation TAG = 'data_hash' def self.trusted_return_type @trusted_return_type ||= Types::PHashType.new(DataProvider.key_type, DataProvider.value_type) end # Performs a lookup with the assumption that a recursive check has been made. # # @param key [LookupKey] The key to lookup # @param lookup_invocation [Invocation] The current lookup invocation # @param merge [MergeStrategy,String,Hash{String => Object},nil] Merge strategy, merge strategy name, strategy and options hash, or nil (implies "first found") # @return [Object] the found object # @throw :no_such_key when the object is not found def unchecked_key_lookup(key, lookup_invocation, merge) root_key = key.root_key lookup_invocation.with(:data_provider, self) do MergeStrategy.strategy(merge).lookup(locations, lookup_invocation) do |location| invoke_with_location(lookup_invocation, location, root_key) end end end private def invoke_with_location(lookup_invocation, location, root_key) if location.nil? lookup_key(lookup_invocation, nil, root_key) else lookup_invocation.with(:location, location) do if location.exist? lookup_key(lookup_invocation, location, root_key) else lookup_invocation.report_location_not_found throw :no_such_key end end end end def lookup_key(lookup_invocation, location, root_key) lookup_invocation.report_found(root_key, data_value(lookup_invocation, location, root_key)) end def data_value(lookup_invocation, location, root_key) hash = data_hash(lookup_invocation, location) value = hash[root_key] if value.nil? && !hash.include?(root_key) lookup_invocation.report_not_found(root_key) throw :no_such_key end value = validate_data_value(value) do msg = "Value for key '#{root_key}', in hash returned from #{full_name}" location.nil? ? msg : "#{msg}, when using location '#{location}'," end interpolate(value, lookup_invocation, true) end def data_hash(lookup_invocation, location) ctx = function_context(lookup_invocation, location) ctx.data_hash ||= parent_data_provider.validate_data_hash(call_data_hash_function(ctx, lookup_invocation, location)) do msg = "Value returned from #{full_name}" location.nil? ? msg : "#{msg}, when using location '#{location}'," end end def call_data_hash_function(ctx, lookup_invocation, location) ctx.function.call(lookup_invocation.scope, options(location), Context.new(ctx, lookup_invocation)) end end # @api private class V3DataHashFunctionProvider < DataHashFunctionProvider TAG = 'v3_data_hash' def initialize(name, parent_data_provider, function_name, options, locations) @datadir = options.delete(HieraConfig::KEY_DATADIR) super end def unchecked_key_lookup(key, lookup_invocation, merge) extra_paths = lookup_invocation.hiera_v3_location_overrides if extra_paths.nil? || extra_paths.empty? super else # Extra paths provided. Must be resolved and placed in front of known paths paths = parent_data_provider.config(lookup_invocation).resolve_paths(@datadir, extra_paths, lookup_invocation, false, ".#{@name}") all_locations = paths + locations root_key = key.root_key lookup_invocation.with(:data_provider, self) do MergeStrategy.strategy(merge).lookup(all_locations, lookup_invocation) do |location| invoke_with_location(lookup_invocation, location, root_key) end end end end end # TODO: API 5.0, remove this class # @api private class V4DataHashFunctionProvider < DataHashFunctionProvider TAG = 'v4_data_hash' def name "Deprecated API function \"#{function_name}\"" end def full_name "deprecated API function '#{function_name}'" end def call_data_hash_function(ctx, lookup_invocation, location) ctx.function.call(lookup_invocation.scope) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/invocation.rb
lib/puppet/pops/lookup/invocation.rb
# frozen_string_literal: true require_relative '../../../puppet/thread_local' require_relative 'explainer' module Puppet::Pops module Lookup # @api private class Invocation attr_reader :scope, :override_values, :default_values, :explainer, :module_name, :top_key, :adapter_class def self.current (@current ||= Puppet::ThreadLocal.new(nil)).value end def self.current=(new_value) @current.value = new_value end # Creates a new instance with same settings as this instance but with a new given scope # and yields with that scope. # # @param scope [Puppet::Parser::Scope] The new scope # @return [Invocation] the new instance def with_scope(scope) yield(Invocation.new(scope, override_values, default_values, explainer)) end # Creates a context object for a lookup invocation. The object contains the current scope, overrides, and default # values and may optionally contain an {ExplanationAcceptor} instance that will receive book-keeping information # about the progress of the lookup. # # If the _explain_ argument is a boolean, then _false_ means that no explanation is needed and _true_ means that # the default explanation acceptor should be used. The _explain_ argument may also be an instance of the # `ExplanationAcceptor` class. # # @param scope [Puppet::Parser::Scope] The scope to use for the lookup # @param override_values [Hash<String,Object>|nil] A map to use as override. Values found here are returned immediately (no merge) # @param default_values [Hash<String,Object>] A map to use as the last resort (but before default) # @param explainer [boolean,Explanainer] An boolean true to use the default explanation acceptor or an explainer instance that will receive information about the lookup def initialize(scope, override_values = EMPTY_HASH, default_values = EMPTY_HASH, explainer = nil, adapter_class = nil) @scope = scope @override_values = override_values @default_values = default_values parent_invocation = self.class.current if parent_invocation && (adapter_class.nil? || adapter_class == parent_invocation.adapter_class) # Inherit from parent invocation (track recursion) @name_stack = parent_invocation.name_stack @adapter_class = parent_invocation.adapter_class # Inherit Hiera 3 legacy properties set_hiera_xxx_call if parent_invocation.hiera_xxx_call? set_hiera_v3_merge_behavior if parent_invocation.hiera_v3_merge_behavior? set_global_only if parent_invocation.global_only? povr = parent_invocation.hiera_v3_location_overrides set_hiera_v3_location_overrides(povr) unless povr.empty? # Inherit explainer unless a new explainer is given or disabled using false explainer = explainer == false ? nil : parent_invocation.explainer else @name_stack = [] @adapter_class = adapter_class.nil? ? LookupAdapter : adapter_class unless explainer.is_a?(Explainer) explainer = explainer == true ? Explainer.new : nil end explainer = DebugExplainer.new(explainer) if Puppet[:debug] && !explainer.is_a?(DebugExplainer) end @explainer = explainer end def lookup(key, module_name = nil) key = LookupKey.new(key) unless key.is_a?(LookupKey) @top_key = key @module_name = module_name.nil? ? key.module_name : module_name save_current = self.class.current if save_current.equal?(self) yield else begin self.class.current = self yield ensure self.class.current = save_current end end end def check(name) if @name_stack.include?(name) raise Puppet::DataBinding::RecursiveLookupError, _("Recursive lookup detected in [%{name_stack}]") % { name_stack: @name_stack.join(', ') } end return unless block_given? @name_stack.push(name) begin yield rescue Puppet::DataBinding::LookupError raise rescue Puppet::Error => detail raise Puppet::DataBinding::LookupError.new(detail.message, nil, nil, nil, detail) ensure @name_stack.pop end end def emit_debug_info(preamble) @explainer.emit_debug_info(preamble) if @explainer.is_a?(DebugExplainer) end # rubocop:disable Naming/MemoizedInstanceVariableName def lookup_adapter @adapter ||= @adapter_class.adapt(scope.compiler) end # rubocop:enable Naming/MemoizedInstanceVariableName # This method is overridden by the special Invocation used while resolving interpolations in a # Hiera configuration file (hiera.yaml) where it's used for collecting and remembering the current # values that the configuration was based on # # @api private def remember_scope_lookup(*lookup_result) # Does nothing by default end # The qualifier_type can be one of: # :global - qualifier is the data binding terminus name # :data_provider - qualifier a DataProvider instance # :path - qualifier is a ResolvedPath instance # :merge - qualifier is a MergeStrategy instance # :interpolation - qualifier is the unresolved interpolation expression # :meta - qualifier is the module name # :data - qualifier is the key # # @param qualifier [Object] A branch, a provider, or a path def with(qualifier_type, qualifier) if explainer.nil? yield else @explainer.push(qualifier_type, qualifier) begin yield ensure @explainer.pop end end end def without_explain if explainer.nil? yield else save_explainer = @explainer begin @explainer = nil yield ensure @explainer = save_explainer end end end def only_explain_options? @explainer.nil? ? false : @explainer.only_explain_options? end def explain_options? @explainer.nil? ? false : @explainer.explain_options? end def report_found_in_overrides(key, value) @explainer.accept_found_in_overrides(key, value) unless @explainer.nil? value end def report_found_in_defaults(key, value) @explainer.accept_found_in_defaults(key, value) unless @explainer.nil? value end def report_found(key, value) @explainer.accept_found(key, value) unless @explainer.nil? value end def report_merge_source(merge_source) @explainer.accept_merge_source(merge_source) unless @explainer.nil? end # Report the result of a merge or fully resolved interpolated string # @param value [Object] The result to report # @return [Object] the given value def report_result(value) @explainer.accept_result(value) unless @explainer.nil? value end def report_not_found(key) @explainer.accept_not_found(key) unless @explainer.nil? end def report_location_not_found @explainer.accept_location_not_found unless @explainer.nil? end def report_module_not_found(module_name) @explainer.accept_module_not_found(module_name) unless @explainer.nil? end def report_module_provider_not_found(module_name) @explainer.accept_module_provider_not_found(module_name) unless @explainer.nil? end def report_text(&block) unless @explainer.nil? @explainer.accept_text(block.call) end end def global_only? lookup_adapter.global_only? || (instance_variable_defined?(:@global_only) ? @global_only : false) end # Instructs the lookup framework to only perform lookups in the global layer # @return [Invocation] self def set_global_only @global_only = true self end # @return [Pathname] the full path of the hiera.yaml config file def global_hiera_config_path lookup_adapter.global_hiera_config_path end # @return [Boolean] `true` if the invocation stems from the hiera_xxx function family def hiera_xxx_call? instance_variable_defined?(:@hiera_xxx_call) end def set_hiera_xxx_call @hiera_xxx_call = true end # @return [Boolean] `true` if the invocation stems from the hiera_xxx function family def hiera_v3_merge_behavior? instance_variable_defined?(:@hiera_v3_merge_behavior) end def set_hiera_v3_merge_behavior @hiera_v3_merge_behavior = true end # Overrides passed from hiera_xxx functions down to V3DataHashFunctionProvider def set_hiera_v3_location_overrides(overrides) @hiera_v3_location_overrides = [overrides].flatten unless overrides.nil? end def hiera_v3_location_overrides instance_variable_defined?(:@hiera_v3_location_overrides) ? @hiera_v3_location_overrides : EMPTY_ARRAY end protected def name_stack @name_stack.clone end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/context.rb
lib/puppet/pops/lookup/context.rb
# frozen_string_literal: true require_relative 'interpolation' module Puppet::Pops module Lookup # The EnvironmentContext is adapted to the current environment # class EnvironmentContext < Adaptable::Adapter class FileData attr_reader :data def initialize(path, inode, mtime, size, data) @path = path @inode = inode @mtime = mtime @size = size @data = data end def valid?(stat) stat.ino == @inode && stat.mtime == @mtime && stat.size == @size end end attr_reader :environment_name def self.create_adapter(environment) new(environment) end def initialize(environment) @environment_name = environment.name @file_data_cache = {} end # Loads the contents of the file given by _path_. The content is then yielded to the provided block in # case a block is given, and the returned value from that block is cached and returned by this method. # If no block is given, the content is stored instead. # # The cache is retained as long as the inode, mtime, and size of the file remains unchanged. # # @param path [String] path to the file to be read # @yieldparam content [String] the content that was read from the file # @yieldreturn [Object] some result based on the content # @return [Object] the content, or if a block was given, the return value of the block # def cached_file_data(path) file_data = @file_data_cache[path] stat = Puppet::FileSystem.stat(path) unless file_data && file_data.valid?(stat) Puppet.debug { "File at '#{path}' was changed, reloading" } if file_data content = Puppet::FileSystem.read(path, :encoding => 'utf-8') file_data = FileData.new(path, stat.ino, stat.mtime, stat.size, block_given? ? yield(content) : content) @file_data_cache[path] = file_data end file_data.data end end # A FunctionContext is created for each unique hierarchy entry and adapted to the Compiler (and hence shares # the compiler's life-cycle). # @api private class FunctionContext include Interpolation attr_reader :module_name, :function attr_accessor :data_hash def initialize(environment_context, module_name, function) @data_hash = nil @cache = {} @environment_context = environment_context @module_name = module_name @function = function end def cache(key, value) @cache[key] = value end def cache_all(hash) @cache.merge!(hash) nil end def cache_has_key(key) @cache.include?(key) end def cached_value(key) @cache[key] end def cached_entries(&block) if block_given? @cache.each_pair do |pair| if block.arity == 2 yield(*pair) else yield(pair) end end nil else Types::Iterable.on(@cache) end end def cached_file_data(path, &block) @environment_context.cached_file_data(path, &block) end def environment_name @environment_context.environment_name end end # The Context is created once for each call to a function. It provides a combination of the {Invocation} object needed # to provide explanation support and the {FunctionContext} object needed to provide the private cache. # The {Context} is part of the public API. It will be passed to a _data_hash_, _data_dig_, or _lookup_key_ function and its # attributes and methods can be used in a Puppet function as well as in a Ruby function. # The {Context} is maps to the Pcore type 'Puppet::LookupContext' # # @api public class Context include Types::PuppetObject extend Forwardable def self._pcore_type @type end def self.register_ptype(loader, ir) tf = Types::TypeFactory key_type = tf.optional(tf.scalar) @type = Pcore.create_object_type( loader, ir, self, 'Puppet::LookupContext', 'Any', { 'environment_name' => { Types::KEY_TYPE => Types::PStringType::NON_EMPTY, Types::KEY_KIND => Types::PObjectType::ATTRIBUTE_KIND_DERIVED }, 'module_name' => { Types::KEY_TYPE => tf.variant(Types::PStringType::NON_EMPTY, Types::PUndefType::DEFAULT) } }, { 'not_found' => tf.callable([0, 0], tf.undef), 'explain' => tf.callable([0, 0, tf.callable(0, 0)], tf.undef), 'interpolate' => tf.callable(1, 1), 'cache' => tf.callable([key_type, tf.any], tf.any), 'cache_all' => tf.callable([tf.hash_kv(key_type, tf.any)], tf.undef), 'cache_has_key' => tf.callable([key_type], tf.boolean), 'cached_value' => tf.callable([key_type], tf.any), 'cached_entries' => tf.variant( tf.callable([0, 0, tf.callable(1, 1)], tf.undef), tf.callable([0, 0, tf.callable(2, 2)], tf.undef), tf.callable([0, 0], tf.iterable(tf.tuple([key_type, tf.any]))) ), 'cached_file_data' => tf.callable(tf.string, tf.optional(tf.callable([1, 1]))) } ).resolve(loader) end # Mainly for test purposes. Makes it possible to create a {Context} in Puppet code provided that a current {Invocation} exists. def self.from_asserted_args(module_name) new(FunctionContext.new(EnvironmentContext.adapt(Puppet.lookup(:environments).get(Puppet[:environment])), module_name, nil), Invocation.current) end # Public methods delegated to the {FunctionContext} def_delegators :@function_context, :cache, :cache_all, :cache_has_key, :cached_value, :cached_entries, :environment_name, :module_name, :cached_file_data def initialize(function_context, lookup_invocation) @lookup_invocation = lookup_invocation @function_context = function_context end # Will call the given block to obtain a textual explanation if explanation support is active. # def explain(&block) @lookup_invocation.report_text(&block) nil end # Resolve interpolation expressions in the given value # @param [Object] value # @return [Object] the value with all interpolation expressions resolved def interpolate(value) @function_context.interpolate(value, @lookup_invocation, true) end def not_found throw :no_such_key end # @api private def invocation @lookup_invocation end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/module_data_provider.rb
lib/puppet/pops/lookup/module_data_provider.rb
# frozen_string_literal: true require_relative 'configured_data_provider' module Puppet::Pops module Lookup # @api private class ModuleDataProvider < ConfiguredDataProvider attr_reader :module_name def initialize(module_name, config = nil) super(config) @module_name = module_name end def place 'Module' end # Performs a lookup using a module default hierarchy with an endless recursion check. # # @param key [LookupKey] The key to lookup # @param lookup_invocation [Invocation] The current lookup invocation # @param merge [MergeStrategy,String,Hash{String=>Object},nil] Merge strategy or hash with strategy and options # def key_lookup_in_default(key, lookup_invocation, merge) dps = config(lookup_invocation).configured_data_providers(lookup_invocation, self, true) if dps.empty? lookup_invocation.report_not_found(key) throw :no_such_key end merge_strategy = MergeStrategy.strategy(merge) lookup_invocation.check(key.to_s) do lookup_invocation.with(:data_provider, self) do merge_strategy.lookup(dps, lookup_invocation) do |data_provider| data_provider.unchecked_key_lookup(key, lookup_invocation, merge_strategy) end end end end # Asserts that all keys in the given _data_hash_ are prefixed with the configured _module_name_. Removes entries # that does not follow the convention and logs a warning. # # @param data_hash [Hash] The data hash # @return [Hash] The possibly pruned hash def validate_data_hash(data_hash) super module_prefix = "#{module_name}::" data_hash_to_return = {} data_hash.keys.each do |k| if k == LOOKUP_OPTIONS || k.start_with?(module_prefix) data_hash_to_return[k] = data_hash[k] else msg = "#{yield} must use keys qualified with the name of the module" Puppet.warning("Module '#{module_name}': #{msg}; got #{k}") end end data_hash_to_return end protected def assert_config_version(config) if config.version > 3 config else if Puppet[:strict] == :error config.fail(Issues::HIERA_VERSION_3_NOT_GLOBAL, :where => 'module') else Puppet.warn_once(:hiera_v3_at_module_root, config.config_path, _('hiera.yaml version 3 found at module root was ignored'), config.config_path) end nil end end # Return the root of the module with the name equal to the configured module name # # @param lookup_invocation [Invocation] The current lookup invocation # @return [Pathname] Path to root of the module # @raise [Puppet::DataBinding::LookupError] if the module can not be found # def provider_root(lookup_invocation) env = lookup_invocation.scope.environment mod = env.module(module_name) raise Puppet::DataBinding::LookupError, _("Environment '%{env}', cannot find module '%{module_name}'") % { env: env.name, module_name: module_name } unless mod Pathname.new(mod.path) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/data_adapter.rb
lib/puppet/pops/lookup/data_adapter.rb
# frozen_string_literal: true module Puppet::Pops module Lookup # A class that adapts a Hash # @api private class DataAdapter < Adaptable::Adapter def self.create_adapter(o) new end def initialize @data = {} end def [](name) @data[name] end def include?(name) @data.include? name end def []=(name, value) @data[name] = value end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/location_resolver.rb
lib/puppet/pops/lookup/location_resolver.rb
# frozen_string_literal: true require 'pathname' require_relative 'interpolation' module Puppet::Pops module Lookup # Class that keeps track of the original location (as it appears in the declaration, before interpolation), # and the fully resolved location, and whether or not the resolved location exists. # # @api private class ResolvedLocation attr_reader :original_location, :location # @param original_location [String] location as found in declaration. May contain interpolation expressions # @param location [Pathname,URI] the expanded location # @param exist [Boolean] `true` if the location is assumed to exist # @api public def initialize(original_location, location, exist) @original_location = original_location @location = location @exist = exist end # @return [Boolean] `true` if the location is assumed to exist # @api public def exist? @exist end # @return the resolved location as a string def to_s @location.to_s end end # Helper methods to resolve interpolated locations # # @api private module LocationResolver include Interpolation def expand_globs(datadir, declared_globs, lookup_invocation) declared_globs.map do |declared_glob| glob = datadir + interpolate(declared_glob, lookup_invocation, false) Pathname.glob(glob).reject(&:directory?).map { |path| ResolvedLocation.new(glob.to_s, path, true) } end.flatten end # @param datadir [Pathname] The base when creating absolute paths # @param declared_paths [Array<String>] paths as found in declaration. May contain interpolation expressions # @param lookup_invocation [Puppet::Pops::Lookup::Invocation] The current lookup invocation # @param is_default_config [Boolean] `true` if this is the default config and non-existent paths should be excluded # @param extension [String] Required extension such as '.yaml' or '.json'. Use only if paths without extension can be expected # @return [Array<ResolvedLocation>] Array of resolved paths def resolve_paths(datadir, declared_paths, lookup_invocation, is_default_config, extension = nil) result = [] declared_paths.each do |declared_path| path = interpolate(declared_path, lookup_invocation, false) path += extension unless extension.nil? || path.end_with?(extension) path = datadir + path path_exists = path.exist? result << ResolvedLocation.new(declared_path, path, path_exists) unless is_default_config && !path_exists end result end # @param declared_uris [Array<String>] paths as found in declaration. May contain interpolation expressions # @param lookup_invocation [Puppet::Pops::Lookup::Invocation] The current lookup invocation # @return [Array<ResolvedLocation>] Array of resolved paths def expand_uris(declared_uris, lookup_invocation) declared_uris.map do |declared_uri| uri = URI(interpolate(declared_uri, lookup_invocation, false)) ResolvedLocation.new(declared_uri, uri, true) end end def expand_mapped_paths(datadir, mapped_path_triplet, lookup_invocation) # The scope interpolation method is used directly to avoid unnecessary parsing of the string that otherwise # would need to be generated mapped_vars = interpolate_method(:scope).call(mapped_path_triplet[0], lookup_invocation, 'mapped_path[0]') # No paths here unless the scope lookup returned something return EMPTY_ARRAY if mapped_vars.nil? || mapped_vars.empty? mapped_vars = [mapped_vars] if mapped_vars.is_a?(String) var_key = mapped_path_triplet[1] template = mapped_path_triplet[2] scope = lookup_invocation.scope lookup_invocation.with_local_memory_eluding(var_key) do mapped_vars.map do |var| # Need to use parent lookup invocation to avoid adding 'var' to the set of variables to track for changes. The # variable that 'var' stems from is added above. path = scope.with_local_scope(var_key => var) { datadir + interpolate(template, lookup_invocation, false) } ResolvedLocation.new(template, path, path.exist?) end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup/configured_data_provider.rb
lib/puppet/pops/lookup/configured_data_provider.rb
# frozen_string_literal: true require_relative 'hiera_config' require_relative 'data_provider' module Puppet::Pops module Lookup # @api private class ConfiguredDataProvider include DataProvider # @param config [HieraConfig,nil] the configuration def initialize(config = nil) @config = config.nil? ? nil : assert_config_version(config) end def config(lookup_invocation) @config ||= assert_config_version(HieraConfig.create(lookup_invocation, configuration_path(lookup_invocation), self)) end # Needed to assign generated version 4 config # @deprecated def config=(config) @config = config end # @return [Pathname] the path to the configuration def config_path @config.nil? ? nil : @config.config_path end # @return [String] the name of this provider def name n = "#{place} " n << '"' << module_name << '" ' unless module_name.nil? n << 'Data Provider' n << " (#{@config.name})" unless @config.nil? n end # Performs a lookup by searching all configured locations for the given _key_. A merge will be performed if # the value is found in more than one location. # # @param key [String] The key to lookup # @param lookup_invocation [Invocation] The current lookup invocation # @param merge [MergeStrategy,String,Hash{String => Object},nil] Merge strategy, merge strategy name, strategy and options hash, or nil (implies "first found") # @return [Object] the found object # @throw :no_such_key when the object is not found def unchecked_key_lookup(key, lookup_invocation, merge) lookup_invocation.with(:data_provider, self) do merge_strategy = MergeStrategy.strategy(merge) dps = data_providers(lookup_invocation) if dps.empty? lookup_invocation.report_not_found(key) throw :no_such_key end merge_strategy.lookup(dps, lookup_invocation) do |data_provider| data_provider.unchecked_key_lookup(key, lookup_invocation, merge_strategy) end end end protected # Assert that the given config version is accepted by this data provider. # # @param config [HieraConfig] the configuration to check # @return [HieraConfig] the argument # @raise [Puppet::DataBinding::LookupError] if the configuration version is unacceptable def assert_config_version(config) config end # Return the root of the configured entity # # @param lookup_invocation [Invocation] The current lookup invocation # @return [Pathname] Path to root of the module # @raise [Puppet::DataBinding::LookupError] if the given module is can not be found # def provider_root(lookup_invocation) raise NotImplementedError, "#{self.class.name} must implement method '#provider_root'" end def configuration_path(lookup_invocation) provider_root(lookup_invocation) + HieraConfig::CONFIG_FILE_NAME end private def data_providers(lookup_invocation) config(lookup_invocation).configured_data_providers(lookup_invocation, self) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/puppet_proc.rb
lib/puppet/pops/evaluator/puppet_proc.rb
# frozen_string_literal: true # Complies with Proc API by mapping a Puppet::Pops::Evaluator::Closure to a ruby Proc. # Creating and passing an instance of this class instead of just a plain block makes # it possible to inherit the parameter info and arity from the closure. Advanced users # may also access the closure itself. The Puppet::Pops::Functions::Dispatcher uses this # when it needs to get the Callable type of the closure. # # The class is part of the Puppet Function API for Ruby and thus public API but a user # should never create an instance of this class. # # @api public class Puppet::Pops::Evaluator::PuppetProc < Proc # Creates a new instance from a closure and a block that will dispatch # all parameters to the closure. The block must be similar to: # # { |*args| closure.call(*args) } # # @param closure [Puppet::Pops::Evaluator::Closure] The closure to map # @param &block [Block] The varargs block that invokes the closure.call method # # @api private def self.new(closure, &block) proc = super(&block) proc.instance_variable_set(:@closure, closure) proc end # @return [Puppet::Pops::Evaluator::Closure] the mapped closure # @api public attr_reader :closure # @overrides Block.lambda? # @return [Boolean] always false since this proc doesn't do the Ruby lambda magic # @api public def lambda? false end # Maps the closure parameters to standard Block parameter info where each # parameter is represented as a two element Array where the first # element is :req, :opt, or :rest and the second element is the name # of the parameter. # # @return [Array<Array<Symbol>>] array of parameter info pairs # @overrides Block.parameters # @api public def parameters @closure.parameters.map do |param| sym = param.name.to_sym if param.captures_rest [:rest, sym] elsif param.value [:opt, sym] else [:req, sym] end end end # @return [Integer] the arity of the block # @overrides Block.arity # @api public def arity parameters.reduce(0) do |memo, param| count = memo + 1 break -count unless param[0] == :req count end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/collector_transformer.rb
lib/puppet/pops/evaluator/collector_transformer.rb
# frozen_string_literal: true module Puppet::Pops module Evaluator class CollectorTransformer def initialize @@query_visitor ||= Visitor.new(nil, "query", 1, 1) @@match_visitor ||= Visitor.new(nil, "match", 1, 1) @@evaluator ||= EvaluatorImpl.new @@compare_operator ||= CompareOperator.new() end def transform(o, scope) # TRANSLATORS 'CollectExpression' is a class name and should not be translated raise ArgumentError, _("Expected CollectExpression") unless o.is_a? Model::CollectExpression raise "LHS is not a type" unless o.type_expr.is_a? Model::QualifiedReference type = o.type_expr.value().downcase() if type == 'class' fail "Classes cannot be collected" end resource_type = Runtime3ResourceSupport.find_resource_type(scope, type) fail "Resource type #{type} doesn't exist" unless resource_type unless o.operations.empty? overrides = { :parameters => o.operations.map { |x| @@evaluator.evaluate(x, scope) }.flatten, :file => o.file, :line => o.line, :source => scope.source, :scope => scope } end code = query_unless_nop(o.query, scope) case o.query when Model::VirtualQuery newcoll = Collectors::CatalogCollector.new(scope, resource_type, code, overrides) when Model::ExportedQuery match = match_unless_nop(o.query, scope) newcoll = Collectors::ExportedCollector.new(scope, resource_type, match, code, overrides) end scope.compiler.add_collection(newcoll) newcoll end protected def query(o, scope) @@query_visitor.visit_this_1(self, o, scope) end def match(o, scope) @@match_visitor.visit_this_1(self, o, scope) end def query_unless_nop(query, scope) unless query.expr.nil? || query.expr.is_a?(Model::Nop) query(query.expr, scope) end end def match_unless_nop(query, scope) unless query.expr.nil? || query.expr.is_a?(Model::Nop) match(query.expr, scope) end end def query_AndExpression(o, scope) left_code = query(o.left_expr, scope) right_code = query(o.right_expr, scope) proc do |resource| left_code.call(resource) && right_code.call(resource) end end def query_OrExpression(o, scope) left_code = query(o.left_expr, scope) right_code = query(o.right_expr, scope) proc do |resource| left_code.call(resource) || right_code.call(resource) end end def query_ComparisonExpression(o, scope) left_code = query(o.left_expr, scope) right_code = query(o.right_expr, scope) case o.operator when '==' if left_code == "tag" # Ensure that to_s and downcase is done once, i.e. outside the proc block and # then use raw_tagged? instead of tagged? if right_code.is_a?(Array) tags = right_code else tags = [right_code] end tags = tags.collect do |t| raise ArgumentError, _('Cannot transform a number to a tag') if t.is_a?(Numeric) t.to_s.downcase end proc do |resource| resource.raw_tagged?(tags) end else proc do |resource| if (tmp = resource[left_code]).is_a?(Array) @@compare_operator.include?(tmp, right_code, scope) else @@compare_operator.equals(tmp, right_code) end end end when '!=' proc do |resource| !@@compare_operator.equals(resource[left_code], right_code) end end end def query_AccessExpression(o, scope) pops_object = @@evaluator.evaluate(o, scope) # Convert to Puppet 3 style objects since that is how they are represented # in the catalog. @@evaluator.convert(pops_object, scope, nil) end def query_VariableExpression(o, scope) @@evaluator.evaluate(o, scope) end def query_LiteralBoolean(o, scope) @@evaluator.evaluate(o, scope) end def query_LiteralString(o, scope) @@evaluator.evaluate(o, scope) end def query_ConcatenatedString(o, scope) @@evaluator.evaluate(o, scope) end def query_LiteralNumber(o, scope) @@evaluator.evaluate(o, scope) end def query_LiteralUndef(o, scope) nil end def query_QualifiedName(o, scope) @@evaluator.evaluate(o, scope) end def query_ParenthesizedExpression(o, scope) query(o.expr, scope) end def query_Object(o, scope) raise ArgumentError, _("Cannot transform object of class %{klass}") % { klass: o.class } end def match_AccessExpression(o, scope) pops_object = @@evaluator.evaluate(o, scope) # Convert to Puppet 3 style objects since that is how they are represented # in the catalog. @@evaluator.convert(pops_object, scope, nil) end def match_AndExpression(o, scope) left_match = match(o.left_expr, scope) right_match = match(o.right_expr, scope) [left_match, 'and', right_match] end def match_OrExpression(o, scope) left_match = match(o.left_expr, scope) right_match = match(o.right_expr, scope) [left_match, 'or', right_match] end def match_ComparisonExpression(o, scope) left_match = match(o.left_expr, scope) right_match = match(o.right_expr, scope) [left_match, o.operator.to_s, right_match] end def match_VariableExpression(o, scope) @@evaluator.evaluate(o, scope) end def match_LiteralBoolean(o, scope) @@evaluator.evaluate(o, scope) end def match_LiteralString(o, scope) @@evaluator.evaluate(o, scope) end def match_LiteralUndef(o, scope) nil end def match_ConcatenatedString(o, scope) @@evaluator.evaluate(o, scope) end def match_LiteralNumber(o, scope) @@evaluator.evaluate(o, scope) end def match_QualifiedName(o, scope) @@evaluator.evaluate(o, scope) end def match_ParenthesizedExpression(o, scope) match(o.expr, scope) end def match_Object(o, scope) raise ArgumentError, _("Cannot transform object of class %{klass}") % { klass: o.class } end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/runtime3_converter.rb
lib/puppet/pops/evaluator/runtime3_converter.rb
# frozen_string_literal: true module Puppet::Pops::Evaluator # Converts nested 4x supported values to 3x values. This is required because # resources and other objects do not know about the new type system, and does not support # regular expressions. Unfortunately this has to be done for array and hash as well. # A complication is that catalog types needs to be resolved against the scope. # # Users should not create instances of this class. Instead the class methods {Runtime3Converter.convert}, # {Runtime3Converter.map_args}, or {Runtime3Converter.instance} should be used class Runtime3Converter MAX_INTEGER = Puppet::Pops::MAX_INTEGER MIN_INTEGER = Puppet::Pops::MIN_INTEGER # Converts 4x supported values to a 3x values. Same as calling Runtime3Converter.instance.map_args(...) # # @param args [Array] Array of values to convert # @param scope [Puppet::Parser::Scope] The scope to use when converting # @param undef_value [Object] The value that nil is converted to # @return [Array] The converted values # def self.map_args(args, scope, undef_value) @instance.map_args(args, scope, undef_value) end # Converts 4x supported values to a 3x values. Same as calling Runtime3Converter.instance.convert(...) # # @param o [Object]The value to convert # @param scope [Puppet::Parser::Scope] The scope to use when converting # @param undef_value [Object] The value that nil is converted to # @return [Object] The converted value # def self.convert(o, scope, undef_value) @instance.convert(o, scope, undef_value) end # Returns the singleton instance of this class. # @return [Runtime3Converter] The singleton instance def self.instance @instance end # Converts 4x supported values to a 3x values. # # @param args [Array] Array of values to convert # @param scope [Puppet::Parser::Scope] The scope to use when converting # @param undef_value [Object] The value that nil is converted to # @return [Array] The converted values # def map_args(args, scope, undef_value) args.map { |a| convert(a, scope, undef_value) } end # Converts a 4x supported value to a 3x value. # # @param o [Object]The value to convert # @param scope [Puppet::Parser::Scope] The scope to use when converting # @param undef_value [Object] The value that nil is converted to # @return [Object] The converted value # def convert(o, scope, undef_value) @convert_visitor.visit_this_2(self, o, scope, undef_value) end def convert_NilClass(o, scope, undef_value) @inner ? nil : undef_value end def convert_Integer(o, scope, undef_value) return o unless o < MIN_INTEGER || o > MAX_INTEGER range_end = o > MAX_INTEGER ? 'max' : 'min' raise Puppet::Error, "Use of a Ruby Integer outside of Puppet Integer #{range_end} range, got '#{'0x%x' % o}'" end def convert_BigDecimal(o, scope, undef_value) # transform to same value float value if possible without any rounding error f = o.to_f return f unless f != o raise Puppet::Error, "Use of a Ruby BigDecimal value outside Puppet Float range, got '#{o}'" end def convert_String(o, scope, undef_value) # Although wasteful, a dup is needed because user code may mutate these strings when applying # Resources. This does not happen when in server mode since it only uses Resources that are # in puppet core and those are all safe. o.frozen? && !Puppet.run_mode.server? ? o.dup : o end def convert_Object(o, scope, undef_value) o end def convert_Array(o, scope, undef_value) ic = @inner_converter o.map { |x| ic.convert(x, scope, undef_value) } end def convert_Hash(o, scope, undef_value) result = {} ic = @inner_converter o.each { |k, v| result[ic.convert(k, scope, undef_value)] = ic.convert(v, scope, undef_value) } result end def convert_Iterator(o, scope, undef_value) raise Puppet::Error, _('Use of an Iterator is not supported here') end def convert_Symbol(o, scope, undef_value) return o unless o == :undef !@inner ? undef_value : nil end def convert_PAnyType(o, scope, undef_value) o end def convert_PCatalogEntryType(o, scope, undef_value) # Since 4x does not support dynamic scoping, all names are absolute and can be # used as is (with some check/transformation/mangling between absolute/relative form # due to Puppet::Resource's idiosyncratic behavior where some references must be # absolute and others cannot be. # Thus there is no need to call scope.resolve_type_and_titles to do dynamic lookup. t, title = catalog_type_to_split_type_title(o) t = Runtime3ResourceSupport.find_resource_type(scope, t) unless t == 'class' || t == 'node' Puppet::Resource.new(t, title) end # Produces an array with [type, title] from a PCatalogEntryType # This method is used to produce the arguments for creation of reference resource instances # (used when 3x is operating on a resource). # Ensures that resources are *not* absolute. # def catalog_type_to_split_type_title(catalog_type) split_type = catalog_type.is_a?(Puppet::Pops::Types::PTypeType) ? catalog_type.type : catalog_type case split_type when Puppet::Pops::Types::PClassType class_name = split_type.class_name ['class', class_name.nil? ? nil : class_name.sub(/^::/, '')] when Puppet::Pops::Types::PResourceType type_name = split_type.type_name title = split_type.title if type_name =~ /^(::)?[Cc]lass$/ ['class', title.nil? ? nil : title.sub(/^::/, '')] else # Ensure that title is '' if nil # Resources with absolute name always results in error because tagging does not support leading :: [type_name.nil? ? nil : type_name.sub(/^::/, '').downcase, title.nil? ? '' : title] end else # TRANSLATORS 'PClassType' and 'PResourceType' are Puppet types and should not be translated raise ArgumentError, _("Cannot split the type %{class_name}, it represents neither a PClassType, nor a PResourceType.") % { class_name: catalog_type.class } end end protected def initialize(inner = false) @inner = inner @inner_converter = inner ? self : self.class.new(true) @convert_visitor = Puppet::Pops::Visitor.new(self, 'convert', 2, 2) end @instance = new end # A Ruby function written for the 3.x API cannot be expected to handle extended data types. This # converter ensures that they are converted to String format # @api private class Runtime3FunctionArgumentConverter < Runtime3Converter def convert_Regexp(o, scope, undef_value) # Puppet 3x cannot handle parameter values that are regular expressions. Turn into regexp string in # source form o.inspect end def convert_Version(o, scope, undef_value) # Puppet 3x cannot handle SemVers. Use the string form o.to_s end def convert_VersionRange(o, scope, undef_value) # Puppet 3x cannot handle SemVerRanges. Use the string form o.to_s end def convert_Binary(o, scope, undef_value) # Puppet 3x cannot handle Binary. Use the string form o.to_s end def convert_Timespan(o, scope, undef_value) # Puppet 3x cannot handle Timespans. Use the string form o.to_s end def convert_Timestamp(o, scope, undef_value) # Puppet 3x cannot handle Timestamps. Use the string form o.to_s end # Converts result back to 4.x by replacing :undef with nil in Array and Hash objects # def self.convert_return(val3x) case val3x when :undef nil when Array val3x.map { |v| convert_return(v) } when Hash hsh = {} val3x.each_pair { |k, v| hsh[convert_return(k)] = convert_return(v) } hsh else val3x end end @instance = new end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/literal_evaluator.rb
lib/puppet/pops/evaluator/literal_evaluator.rb
# frozen_string_literal: true module Puppet::Pops module Evaluator # Literal values for # String (not containing interpolation) # Numbers # Booleans # Undef (produces nil) # Array # Hash # QualifiedName # Default (produced :default) # Regular Expression (produces ruby regular expression) # QualifiedReference # AccessExpresion # class LiteralEvaluator COMMA_SEPARATOR = ', ' def initialize @@literal_visitor ||= Visitor.new(self, "literal", 0, 0) end def literal(ast) @@literal_visitor.visit_this_0(self, ast) end def literal_Object(o) throw :not_literal end def literal_Factory(o) literal(o.model) end def literal_Program(o) literal(o.body) end def literal_LiteralString(o) o.value end def literal_QualifiedName(o) o.value end def literal_LiteralNumber(o) o.value end def literal_LiteralBoolean(o) o.value end def literal_LiteralUndef(o) nil end def literal_LiteralDefault(o) :default end def literal_LiteralRegularExpression(o) o.value end def literal_QualifiedReference(o) o.value end def literal_AccessExpression(o) # to prevent parameters with [[]] like Optional[[String]] throw :not_literal if o.keys.size == 1 && o.keys[0].is_a?(Model::LiteralList) o.keys.map { |v| literal(v) } end def literal_UnaryMinusExpression(o) -literal(o.expr) end def literal_ConcatenatedString(o) # use double quoted string value if there is no interpolation throw :not_literal unless o.segments.size == 1 && o.segments[0].is_a?(Model::LiteralString) o.segments[0].value end def literal_LiteralList(o) o.values.map { |v| literal(v) } end def literal_LiteralHash(o) o.entries.each_with_object({}) do |entry, result| result[literal(entry.key)] = literal(entry.value) end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/external_syntax_support.rb
lib/puppet/pops/evaluator/external_syntax_support.rb
# frozen_string_literal: true # This module is an integral part of the evaluator. It deals with the concern of validating # external syntax in text produced by heredoc and templates. # require_relative '../../../puppet/plugins/syntax_checkers' module Puppet::Pops::Evaluator::ExternalSyntaxSupport def assert_external_syntax(_, result, syntax, reference_expr) # ignore 'unspecified syntax' return if syntax.nil? || syntax == '' checker = checker_for_syntax(nil, syntax) # ignore syntax with no matching checker return unless checker # Call checker and give it the location information from the expression # (as opposed to where the heredoc tag is (somewhere on the line above)). acceptor = Puppet::Pops::Validation::Acceptor.new() checker.check(result, syntax, acceptor, reference_expr) if acceptor.error_count > 0 checker_message = "Invalid produced text having syntax: '#{syntax}'." Puppet::Pops::IssueReporter.assert_and_report(acceptor, :message => checker_message) raise ArgumentError, _("Internal Error: Configuration of runtime error handling wrong: should have raised exception") end end # Finds the most significant checker for the given syntax (most significant is to the right). # Returns nil if there is no registered checker. # def checker_for_syntax(_, syntax) checkers_hash = Puppet.lookup(:plugins)[Puppet::Plugins::SyntaxCheckers::SYNTAX_CHECKERS_KEY] checkers_hash[lookup_keys_for_syntax(syntax).find { |x| checkers_hash[x] }] end # Returns an array of possible syntax names def lookup_keys_for_syntax(syntax) segments = syntax.split(/\+/) result = [] loop do result << segments.join("+") segments.shift break if segments.empty? end result end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/access_operator.rb
lib/puppet/pops/evaluator/access_operator.rb
# frozen_string_literal: true module Puppet::Pops module Evaluator # AccessOperator handles operator [] # This operator is part of evaluation. # class AccessOperator # Provides access to the Puppet 3.x runtime (scope, etc.) # This separation has been made to make it easier to later migrate the evaluator to an improved runtime. # include Runtime3Support attr_reader :semantic # Initialize with AccessExpression to enable reporting issues # @param access_expression [Model::AccessExpression] the semantic object being evaluated # @return [void] # def initialize(access_expression) @@access_visitor ||= Visitor.new(self, "access", 2, nil) @semantic = access_expression end def access(o, scope, *keys) @@access_visitor.visit_this_2(self, o, scope, keys) end protected def access_Object(o, scope, keys) type = Puppet::Pops::Types::TypeCalculator.infer_callable_methods_t(o) if type.is_a?(Puppet::Pops::Types::TypeWithMembers) access_func = type['[]'] return access_func.invoke(o, scope, keys) unless access_func.nil? end fail(Issues::OPERATOR_NOT_APPLICABLE, @semantic.left_expr, :operator => '[]', :left_value => o) end def access_Binary(o, scope, keys) Puppet::Pops::Types::PBinaryType::Binary.from_binary_string(access_String(o.binary_buffer, scope, keys)) end def access_String(o, scope, keys) keys.flatten! result = case keys.size when 0 fail(Issues::BAD_STRING_SLICE_ARITY, @semantic.left_expr, { :actual => keys.size }) when 1 # Note that Ruby 1.8.7 requires a length of 1 to produce a String k1 = Utils.to_n(keys[0]) bad_string_access_key_type(o, 0, k1.nil? ? keys[0] : k1) unless k1.is_a?(Integer) k2 = 1 k1 = k1 < 0 ? o.length + k1 : k1 # abs pos # if k1 is outside, a length of 1 always produces an empty string if k1 < 0 EMPTY_STRING else o[k1, k2] end when 2 k1 = Utils.to_n(keys[0]) k2 = Utils.to_n(keys[1]) [k1, k2].each_with_index { |k, i| bad_string_access_key_type(o, i, k.nil? ? keys[i] : k) unless k.is_a?(Integer) } k1 = k1 < 0 ? o.length + k1 : k1 # abs pos (negative is count from end) k2 = k2 < 0 ? o.length - k1 + k2 + 1 : k2 # abs length (negative k2 is length from pos to end count) # if k1 is outside, adjust to first position, and adjust length if k1 < 0 k2 += k1 k1 = 0 end o[k1, k2] else fail(Issues::BAD_STRING_SLICE_ARITY, @semantic.left_expr, { :actual => keys.size }) end # Specified as: an index outside of range, or empty result == empty string (result.nil? || result.empty?) ? EMPTY_STRING : result end # Parameterizes a PRegexp Type with a pattern string or r ruby egexp # def access_PRegexpType(o, scope, keys) keys.flatten! unless keys.size == 1 blamed = keys.size == 0 ? @semantic : @semantic.keys[1] fail(Issues::BAD_TYPE_SLICE_ARITY, blamed, :base_type => o, :min => 1, :actual => keys.size) end assert_keys(keys, o, 1, 1, String, Regexp) Types::TypeFactory.regexp(*keys) end # Evaluates <ary>[] with 1 or 2 arguments. One argument is an index lookup, two arguments is a slice from/to. # def access_Array(o, scope, keys) keys.flatten! case keys.size when 0 fail(Issues::BAD_ARRAY_SLICE_ARITY, @semantic.left_expr, { :actual => keys.size }) when 1 key = coerce_numeric(keys[0], @semantic.keys[0], scope) unless key.is_a?(Integer) bad_access_key_type(o, 0, key, Integer) end o[key] when 2 # A slice [from, to] with support for -1 to mean start, or end respectively. k1 = coerce_numeric(keys[0], @semantic.keys[0], scope) k2 = coerce_numeric(keys[1], @semantic.keys[1], scope) [k1, k2].each_with_index { |k, i| bad_access_key_type(o, i, k, Integer) unless k.is_a?(Integer) } # Help confused Ruby do the right thing (it truncates to the right, but negative index + length can never overlap # the available range. k1 = k1 < 0 ? o.length + k1 : k1 # abs pos (negative is count from end) k2 = k2 < 0 ? o.length - k1 + k2 + 1 : k2 # abs length (negative k2 is length from pos to end count) # if k1 is outside, adjust to first position, and adjust length if k1 < 0 k2 += k1 k1 = 0 end # Help ruby always return empty array when asking for a sub array result = o[k1, k2] result.nil? ? [] : result else fail(Issues::BAD_ARRAY_SLICE_ARITY, @semantic.left_expr, { :actual => keys.size }) end end # Evaluates <hsh>[] with support for one or more arguments. If more than one argument is used, the result # is an array with each lookup. # @note # Does not flatten its keys to enable looking up with a structure # def access_Hash(o, scope, keys) # Look up key in hash, if key is nil, try alternate form (:undef) before giving up. # This is done because the hash may have been produced by 3x logic and may thus contain :undef. result = keys.collect do |k| o.fetch(k) { |key| key.nil? ? o[:undef] : nil } end case result.size when 0 fail(Issues::BAD_HASH_SLICE_ARITY, @semantic.left_expr, { :actual => keys.size }) when 1 result.pop else # remove nil elements and return result.compact! result end end def access_PBooleanType(o, scope, keys) keys.flatten! assert_keys(keys, o, 1, 1, TrueClass, FalseClass) Types::TypeFactory.boolean(keys[0]) end def access_PEnumType(o, scope, keys) keys.flatten! last = keys.last case_insensitive = false if last == true || last == false keys = keys[0...-1] case_insensitive = last end assert_keys(keys, o, 1, Float::INFINITY, String) Types::PEnumType.new(keys, case_insensitive) end def access_PVariantType(o, scope, keys) keys.flatten! assert_keys(keys, o, 1, Float::INFINITY, Types::PAnyType) Types::TypeFactory.variant(*keys) end def access_PSemVerType(o, scope, keys) keys.flatten! assert_keys(keys, o, 1, Float::INFINITY, String, SemanticPuppet::VersionRange) Types::TypeFactory.sem_ver(*keys) end def access_PTimestampType(o, scope, keys) keys.flatten! fail(Issues::BAD_TYPE_SLICE_ARITY, @semantic, :base_type => o, :min => 0, :max => 2, :actual => keys.size) if keys.size > 2 Types::TypeFactory.timestamp(*keys) end def access_PTimespanType(o, scope, keys) keys.flatten! fail(Issues::BAD_TYPE_SLICE_ARITY, @semantic, :base_type => o, :min => 0, :max => 2, :actual => keys.size) if keys.size > 2 Types::TypeFactory.timespan(*keys) end def access_PTupleType(o, scope, keys) keys.flatten! if Types::TypeFactory.is_range_parameter?(keys[-2]) && Types::TypeFactory.is_range_parameter?(keys[-1]) size_type = Types::TypeFactory.range(keys[-2], keys[-1]) keys = keys[0, keys.size - 2] elsif Types::TypeFactory.is_range_parameter?(keys[-1]) size_type = Types::TypeFactory.range(keys[-1], :default) keys = keys[0, keys.size - 1] end assert_keys(keys, o, 1, Float::INFINITY, Types::PAnyType) Types::TypeFactory.tuple(keys, size_type) end def access_PCallableType(o, scope, keys) if keys.size > 0 && keys[0].is_a?(Array) unless keys.size == 2 fail(Issues::BAD_TYPE_SLICE_ARITY, @semantic, :base_type => o, :min => 2, :max => 2, :actual => keys.size) end unless keys[1].is_a?(Types::PAnyType) bad_type_specialization_key_type(o, 1, k, Types::PAnyType) end end Types::TypeFactory.callable(*keys) end def access_PStructType(o, scope, keys) assert_keys(keys, o, 1, 1, Hash) Types::TypeFactory.struct(keys[0]) end def access_PStringType(o, scope, keys) keys.flatten! case keys.size when 1 size_t = collection_size_t(0, keys[0]) when 2 size_t = collection_size_t(0, keys[0], keys[1]) else fail(Issues::BAD_STRING_SLICE_ARITY, @semantic, { :actual => keys.size }) end Types::TypeFactory.string(size_t) end # Asserts type of each key and calls fail with BAD_TYPE_SPECIFICATION # @param keys [Array<Object>] the evaluated keys # @param o [Object] evaluated LHS reported as :base_type # @param min [Integer] the minimum number of keys (typically 1) # @param max [Numeric] the maximum number of keys (use same as min, specific number, or Float::INFINITY) # @param allowed_classes [Class] a variable number of classes that each key must be an instance of (any) # @api private # def assert_keys(keys, o, min, max, *allowed_classes) size = keys.size unless size.between?(min, max || Float::INFINITY) fail(Issues::BAD_TYPE_SLICE_ARITY, @semantic, :base_type => o, :min => 1, :max => max, :actual => keys.size) end keys.each_with_index do |k, i| unless allowed_classes.any? { |clazz| k.is_a?(clazz) } bad_type_specialization_key_type(o, i, k, *allowed_classes) end end end def bad_access_key_type(lhs, key_index, actual, *expected_classes) fail(Issues::BAD_SLICE_KEY_TYPE, @semantic.keys[key_index], { :left_value => lhs, :actual => bad_key_type_name(actual), :expected_classes => expected_classes }) end def bad_string_access_key_type(lhs, key_index, actual) fail(Issues::BAD_STRING_SLICE_KEY_TYPE, @semantic.keys[key_index], { :left_value => lhs, :actual_type => bad_key_type_name(actual), }) end def bad_key_type_name(actual) case actual when nil 'Undef' when :default 'Default' else Types::TypeCalculator.generalize(Types::TypeCalculator.infer(actual)).to_s end end def bad_type_specialization_key_type(type, key_index, actual, *expected_classes) label_provider = Model::ModelLabelProvider.new() expected = expected_classes.map { |c| label_provider.label(c) }.join(' or ') fail(Issues::BAD_TYPE_SPECIALIZATION, @semantic.keys[key_index], { :type => type, :message => _("Cannot use %{key} where %{expected} is expected") % { key: bad_key_type_name(actual), expected: expected } }) end def access_PPatternType(o, scope, keys) keys.flatten! assert_keys(keys, o, 1, Float::INFINITY, String, Regexp, Types::PPatternType, Types::PRegexpType) Types::TypeFactory.pattern(*keys) end def access_PURIType(o, scope, keys) keys.flatten! if keys.size == 1 param = keys[0] unless Types::PURIType::TYPE_URI_PARAM_TYPE.instance?(param) fail(Issues::BAD_TYPE_SLICE_TYPE, @semantic.keys[0], { :base_type => 'URI-Type', :actual => param.class }) end Types::PURIType.new(param) else fail(Issues::BAD_TYPE_SLICE_ARITY, @semantic, { :base_type => 'URI-Type', :min => 1, :actual => keys.size }) end end def access_POptionalType(o, scope, keys) keys.flatten! if keys.size == 1 type = keys[0] unless type.is_a?(Types::PAnyType) if type.is_a?(String) type = Types::TypeFactory.string(type) else fail(Issues::BAD_TYPE_SLICE_TYPE, @semantic.keys[0], { :base_type => 'Optional-Type', :actual => type.class }) end end Types::POptionalType.new(type) else fail(Issues::BAD_TYPE_SLICE_ARITY, @semantic, { :base_type => 'Optional-Type', :min => 1, :actual => keys.size }) end end def access_PSensitiveType(o, scope, keys) keys.flatten! if keys.size == 1 type = keys[0] unless type.is_a?(Types::PAnyType) fail(Issues::BAD_TYPE_SLICE_TYPE, @semantic.keys[0], { :base_type => 'Sensitive-Type', :actual => type.class }) end Types::PSensitiveType.new(type) else fail(Issues::BAD_TYPE_SLICE_ARITY, @semantic, { :base_type => 'Sensitive-Type', :min => 1, :actual => keys.size }) end end def access_PObjectType(o, scope, keys) keys.flatten! if o.resolved? && !o.name.nil? Types::PObjectTypeExtension.create(o, keys) elsif keys.size == 1 Types::TypeFactory.object(keys[0]) else fail(Issues::BAD_TYPE_SLICE_ARITY, @semantic, { :base_type => 'Object-Type', :min => 1, :actual => keys.size }) end end def access_PTypeSetType(o, scope, keys) keys.flatten! if keys.size == 1 Types::TypeFactory.type_set(keys[0]) else fail(Issues::BAD_TYPE_SLICE_ARITY, @semantic, { :base_type => 'TypeSet-Type', :min => 1, :actual => keys.size }) end end def access_PNotUndefType(o, scope, keys) keys.flatten! case keys.size when 0 Types::TypeFactory.not_undef when 1 type = keys[0] case type when String type = Types::TypeFactory.string(type) when Types::PAnyType type = nil if type.instance_of?(Types::PAnyType) else fail(Issues::BAD_NOT_UNDEF_SLICE_TYPE, @semantic.keys[0], { :base_type => 'NotUndef-Type', :actual => type.class }) end Types::TypeFactory.not_undef(type) else fail(Issues::BAD_TYPE_SLICE_ARITY, @semantic, { :base_type => 'NotUndef-Type', :min => 0, :max => 1, :actual => keys.size }) end end def access_PTypeType(o, scope, keys) keys.flatten! if keys.size == 1 unless keys[0].is_a?(Types::PAnyType) fail(Issues::BAD_TYPE_SLICE_TYPE, @semantic.keys[0], { :base_type => 'Type-Type', :actual => keys[0].class }) end Types::PTypeType.new(keys[0]) else fail(Issues::BAD_TYPE_SLICE_ARITY, @semantic, { :base_type => 'Type-Type', :min => 1, :actual => keys.size }) end end def access_PInitType(o, scope, keys) unless keys[0].is_a?(Types::PAnyType) fail(Issues::BAD_TYPE_SLICE_TYPE, @semantic.keys[0], { :base_type => 'Init-Type', :actual => keys[0].class }) end Types::TypeFactory.init(*keys) end def access_PIterableType(o, scope, keys) keys.flatten! if keys.size == 1 unless keys[0].is_a?(Types::PAnyType) fail(Issues::BAD_TYPE_SLICE_TYPE, @semantic.keys[0], { :base_type => 'Iterable-Type', :actual => keys[0].class }) end Types::PIterableType.new(keys[0]) else fail(Issues::BAD_TYPE_SLICE_ARITY, @semantic, { :base_type => 'Iterable-Type', :min => 1, :actual => keys.size }) end end def access_PIteratorType(o, scope, keys) keys.flatten! if keys.size == 1 unless keys[0].is_a?(Types::PAnyType) fail(Issues::BAD_TYPE_SLICE_TYPE, @semantic.keys[0], { :base_type => 'Iterator-Type', :actual => keys[0].class }) end Types::PIteratorType.new(keys[0]) else fail(Issues::BAD_TYPE_SLICE_ARITY, @semantic, { :base_type => 'Iterator-Type', :min => 1, :actual => keys.size }) end end def access_PRuntimeType(o, scope, keys) keys.flatten! assert_keys(keys, o, 2, 2, String, String) # create runtime type based on runtime and name of class, (not inference of key's type) Types::TypeFactory.runtime(*keys) end def access_PIntegerType(o, scope, keys) keys.flatten! unless keys.size.between?(1, 2) fail(Issues::BAD_INTEGER_SLICE_ARITY, @semantic, { :actual => keys.size }) end keys.each_with_index do |x, index| fail(Issues::BAD_INTEGER_SLICE_TYPE, @semantic.keys[index], { :actual => x.class }) unless x.is_a?(Integer) || x == :default end Types::PIntegerType.new(*keys) end def access_PFloatType(o, scope, keys) keys.flatten! unless keys.size.between?(1, 2) fail(Issues::BAD_FLOAT_SLICE_ARITY, @semantic, { :actual => keys.size }) end keys.each_with_index do |x, index| fail(Issues::BAD_FLOAT_SLICE_TYPE, @semantic.keys[index], { :actual => x.class }) unless x.is_a?(Float) || x.is_a?(Integer) || x == :default end from, to = keys from = from == :default || from.nil? ? nil : Float(from) to = to == :default || to.nil? ? nil : Float(to) Types::PFloatType.new(from, to) end # A Hash can create a new Hash type, one arg sets value type, two args sets key and value type in new type. # With 3 or 4 arguments, these are used to create a size constraint. # It is not possible to create a collection of Hash types directly. # def access_PHashType(o, scope, keys) keys.flatten! if keys.size == 2 && keys[0].is_a?(Integer) && keys[1].is_a?(Integer) return Types::PHashType.new(nil, nil, Types::PIntegerType.new(*keys)) end keys[0, 2].each_with_index do |k, index| unless k.is_a?(Types::PAnyType) fail(Issues::BAD_TYPE_SLICE_TYPE, @semantic.keys[index], { :base_type => 'Hash-Type', :actual => k.class }) end end case keys.size when 2 size_t = nil when 3 size_t = keys[2] size_t = Types::PIntegerType.new(size_t) unless size_t.is_a?(Types::PIntegerType) when 4 size_t = collection_size_t(2, keys[2], keys[3]) else fail(Issues::BAD_TYPE_SLICE_ARITY, @semantic, { :base_type => 'Hash-Type', :min => 2, :max => 4, :actual => keys.size }) end Types::PHashType.new(keys[0], keys[1], size_t) end # CollectionType is parameterized with a range def access_PCollectionType(o, scope, keys) keys.flatten! case keys.size when 1 size_t = collection_size_t(0, keys[0]) when 2 size_t = collection_size_t(0, keys[0], keys[1]) else fail(Issues::BAD_TYPE_SLICE_ARITY, @semantic, { :base_type => 'Collection-Type', :min => 1, :max => 2, :actual => keys.size }) end Types::PCollectionType.new(size_t) end # An Array can create a new Array type. It is not possible to create a collection of Array types. # def access_PArrayType(o, scope, keys) keys.flatten! case keys.size when 1 unless keys[0].is_a?(Types::PAnyType) fail(Issues::BAD_TYPE_SLICE_TYPE, @semantic.keys[0], { :base_type => 'Array-Type', :actual => keys[0].class }) end type = keys[0] size_t = nil when 2 if keys[0].is_a?(Types::PAnyType) size_t = collection_size_t(1, keys[1]) type = keys[0] else size_t = collection_size_t(0, keys[0], keys[1]) type = nil end when 3 if keys[0].is_a?(Types::PAnyType) size_t = collection_size_t(1, keys[1], keys[2]) type = keys[0] else fail(Issues::BAD_TYPE_SLICE_TYPE, @semantic.keys[0], { :base_type => 'Array-Type', :actual => keys[0].class }) end else fail(Issues::BAD_TYPE_SLICE_ARITY, @semantic, { :base_type => 'Array-Type', :min => 1, :max => 3, :actual => keys.size }) end Types::PArrayType.new(type, size_t) end # Produces an PIntegerType (range) given one or two keys. def collection_size_t(start_index, *keys) if keys.size == 1 && keys[0].is_a?(Types::PIntegerType) keys[0] else keys.each_with_index do |x, index| fail(Issues::BAD_COLLECTION_SLICE_TYPE, @semantic.keys[start_index + index], { :actual => x.class }) unless x.is_a?(Integer) || x == :default end Types::PIntegerType.new(*keys) end end # A Puppet::Resource represents either just a type (no title), or is a fully qualified type/title. # def access_Resource(o, scope, keys) # To access a Puppet::Resource as if it was a PResourceType, simply infer it, and take the type of # the parameterized meta type (i.e. Type[Resource[the_resource_type, the_resource_title]]) t = Types::TypeCalculator.infer(o).type # must map "undefined title" from resource to nil t.title = nil if t.title == EMPTY_STRING access(t, scope, *keys) end # If a type reference is encountered here, it's an error def access_PTypeReferenceType(o, scope, keys) fail(Issues::UNKNOWN_RESOURCE_TYPE, @semantic, { :type_name => o.type_string }) end # A Resource can create a new more specific Resource type, and/or an array of resource types # If the given type has title set, it can not be specified further. # @example # Resource[File] # => File # Resource[File, 'foo'] # => File[foo] # Resource[File. 'foo', 'bar'] # => [File[foo], File[bar]] # File['foo', 'bar'] # => [File[foo], File[bar]] # File['foo']['bar'] # => Value of the 'bar' parameter in the File['foo'] resource # Resource[File]['foo', 'bar'] # => [File[Foo], File[bar]] # Resource[File, 'foo', 'bar'] # => [File[foo], File[bar]] # Resource[File, 'foo']['bar'] # => Value of the 'bar' parameter in the File['foo'] resource # def access_PResourceType(o, scope, keys) blamed = keys.size == 0 ? @semantic : @semantic.keys[0] if keys.size == 0 fail(Issues::BAD_TYPE_SLICE_ARITY, blamed, :base_type => o.to_s, :min => 1, :max => -1, :actual => 0) end # Must know which concrete resource type to operate on in all cases. # It is not allowed to specify the type in an array arg - e.g. Resource[[File, 'foo']] # type_name is LHS type_name if set, else the first given arg type_name = o.type_name || Types::TypeFormatter.singleton.capitalize_segments(keys.shift) type_name = case type_name when Types::PResourceType type_name.type_name when String type_name else # blame given left expression if it defined the type, else the first given key expression blame = o.type_name.nil? ? @semantic.keys[0] : @semantic.left_expr fail(Issues::ILLEGAL_RESOURCE_SPECIALIZATION, blame, { :actual => bad_key_type_name(type_name) }) end # type name must conform if type_name !~ Patterns::CLASSREF_EXT fail(Issues::ILLEGAL_CLASSREF, blamed, { :name => type_name }) end # The result is an array if multiple titles are given, or if titles are specified with an array # (possibly multiple arrays, and nested arrays). result_type_array = keys.size > 1 || keys[0].is_a?(Array) keys_orig_size = keys.size keys.flatten! keys.compact! # If given keys that were just a mix of empty/nil with empty array as a result. # As opposed to calling the function the wrong way (without any arguments), (configurable issue), # Return an empty array # if keys.empty? && keys_orig_size > 0 optionally_fail(Issues::EMPTY_RESOURCE_SPECIALIZATION, blamed) return result_type_array ? [] : nil end unless o.title.nil? # lookup resource and return one or more parameter values resource = find_resource(scope, o.type_name, o.title) unless resource fail(Issues::UNKNOWN_RESOURCE, @semantic, { :type_name => o.type_name, :title => o.title }) end result = keys.map do |k| unless is_parameter_of_resource?(scope, resource, k) fail(Issues::UNKNOWN_RESOURCE_PARAMETER, @semantic, { :type_name => o.type_name, :title => o.title, :param_name => k }) end get_resource_parameter_value(scope, resource, k) end return result_type_array ? result : result.pop end keys = [:no_title] if keys.size < 1 # if there was only a type_name and it was consumed result = keys.each_with_index.map do |t, i| unless t.is_a?(String) || t == :no_title index = keys_orig_size != keys.size ? i + 1 : i fail(Issues::BAD_TYPE_SPECIALIZATION, @semantic.keys[index], { :type => o, :message => "Cannot use #{bad_key_type_name(t)} where a resource title String is expected" }) end Types::PResourceType.new(type_name, t == :no_title ? nil : t) end # returns single type if request was for a single entity, else an array of types (possibly empty) result_type_array ? result : result.pop end NS = '::' def access_PClassType(o, scope, keys) blamed = keys.size == 0 ? @semantic : @semantic.keys[0] keys_orig_size = keys.size if keys_orig_size == 0 fail(Issues::BAD_TYPE_SLICE_ARITY, blamed, :base_type => o.to_s, :min => 1, :max => -1, :actual => 0) end # The result is an array if multiple classnames are given, or if classnames are specified with an array # (possibly multiple arrays, and nested arrays). result_type_array = keys.size > 1 || keys[0].is_a?(Array) keys.flatten! keys.compact! # If given keys that were just a mix of empty/nil with empty array as a result. # As opposed to calling the function the wrong way (without any arguments), (configurable issue), # Return an empty array # if keys.empty? && keys_orig_size > 0 optionally_fail(Issues::EMPTY_RESOURCE_SPECIALIZATION, blamed) return result_type_array ? [] : nil end if o.class_name.nil? result = keys.each_with_index.map do |c, i| fail(Issues::ILLEGAL_HOSTCLASS_NAME, @semantic.keys[i], { :name => c }) unless c.is_a?(String) name = c.downcase # Remove leading '::' since all references are global, and 3x runtime does the wrong thing name = name[2..] if name[0, 2] == NS fail(Issues::ILLEGAL_NAME, @semantic.keys[i], { :name => c }) unless name =~ Patterns::NAME Types::PClassType.new(name) end else # lookup class resource and return one or more parameter values resource = find_resource(scope, 'class', o.class_name) if resource result = keys.map do |k| if is_parameter_of_resource?(scope, resource, k) get_resource_parameter_value(scope, resource, k) else fail(Issues::UNKNOWN_RESOURCE_PARAMETER, @semantic, { :type_name => 'Class', :title => o.class_name, :param_name => k }) end end else fail(Issues::UNKNOWN_RESOURCE, @semantic, { :type_name => 'Class', :title => o.class_name }) end end # returns single type as type, else an array of types result_type_array ? result : result.pop end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/evaluator_impl.rb
lib/puppet/pops/evaluator/evaluator_impl.rb
# frozen_string_literal: true require_relative '../../../puppet/parser/scope' require_relative '../../../puppet/pops/evaluator/compare_operator' require_relative '../../../puppet/pops/evaluator/relationship_operator' require_relative '../../../puppet/pops/evaluator/access_operator' require_relative '../../../puppet/pops/evaluator/closure' require_relative '../../../puppet/pops/evaluator/external_syntax_support' require_relative '../../../puppet/pops/types/iterable' module Puppet::Pops module Evaluator # This implementation of {Evaluator} performs evaluation using the puppet 3.x runtime system # in a manner largely compatible with Puppet 3.x, but adds new features and introduces constraints. # # The evaluation uses _polymorphic dispatch_ which works by dispatching to the first found method named after # the class or one of its super-classes. The EvaluatorImpl itself mainly deals with evaluation (it currently # also handles assignment), and it uses a delegation pattern to more specialized handlers of some operators # that in turn use polymorphic dispatch; this to not clutter EvaluatorImpl with too much responsibility). # # Since a pattern is used, only the main entry points are fully documented. The parameters _o_ and _scope_ are # the same in all the polymorphic methods, (the type of the parameter _o_ is reflected in the method's name; # either the actual class, or one of its super classes). The _scope_ parameter is always the scope in which # the evaluation takes place. If nothing else is mentioned, the return is always the result of evaluation. # # See {Visitable} and {Visitor} for more information about # polymorphic calling. # class EvaluatorImpl include Utils # Provides access to the Puppet 3.x runtime (scope, etc.) # This separation has been made to make it easier to later migrate the evaluator to an improved runtime. # include Runtime3Support include ExternalSyntaxSupport COMMA_SEPARATOR = ', ' def initialize @@initialized ||= static_initialize # Use null migration checker unless given in context @migration_checker = Puppet.lookup(:migration_checker) { Migration::MigrationChecker.singleton } end # @api private def static_initialize @@eval_visitor ||= Visitor.new(self, "eval", 1, 1) @@lvalue_visitor ||= Visitor.new(self, "lvalue", 1, 1) @@assign_visitor ||= Visitor.new(self, "assign", 3, 3) @@string_visitor ||= Visitor.new(self, "string", 1, 1) @@type_calculator ||= Types::TypeCalculator.singleton @@compare_operator ||= CompareOperator.new @@relationship_operator ||= RelationshipOperator.new true end private :static_initialize # @api private def type_calculator @@type_calculator end # Evaluates the given _target_ object in the given scope. # # @overload evaluate(target, scope) # @param target [Object] evaluation target - see methods on the pattern assign_TYPE for actual supported types. # @param scope [Object] the runtime specific scope class where evaluation should take place # @return [Object] the result of the evaluation # # @api public # def evaluate(target, scope) @@eval_visitor.visit_this_1(self, target, scope) rescue SemanticError => e # A raised issue may not know the semantic target, use errors call stack, but fill in the # rest from a supplied semantic object, or the target instruction if there is not semantic # object. # fail(e.issue, e.semantic || target, e.options, e) rescue Puppet::PreformattedError => e # Already formatted with location information, and with the wanted call stack. # Note this is currently a specialized ParseError, so rescue-order is important # raise e rescue Puppet::ParseError => e # ParseError may be raised in ruby code without knowing the location # in puppet code. # Accept a ParseError that has file or line information available # as an error that should be used verbatim. (Tests typically run without # setting a file name). # ParseError can supply an original - it is impossible to determine which # call stack that should be propagated, using the ParseError's backtrace. # if e.file || e.line raise e else # Since it had no location information, treat it as user intended a general purpose # error. Pass on its call stack. fail(Issues::RUNTIME_ERROR, target, { :detail => e.message }, e) end rescue Puppet::Error => e # PuppetError has the ability to wrap an exception, if so, use the wrapped exception's # call stack instead fail(Issues::RUNTIME_ERROR, target, { :detail => e.message }, e.original || e) rescue StopIteration => e # Ensure these are not rescued as StandardError raise e rescue StandardError => e # All other errors, use its message and call stack fail(Issues::RUNTIME_ERROR, target, { :detail => e.message }, e) end # Assigns the given _value_ to the given _target_. The additional argument _o_ is the instruction that # produced the target/value tuple and it is used to set the origin of the result. # # @param target [Object] assignment target - see methods on the pattern assign_TYPE for actual supported types. # @param value [Object] the value to assign to `target` # @param o [Model::PopsObject] originating instruction # @param scope [Object] the runtime specific scope where evaluation should take place # # @api private # def assign(target, value, o, scope) @@assign_visitor.visit_this_3(self, target, value, o, scope) end # Computes a value that can be used as the LHS in an assignment. # @param o [Object] the expression to evaluate as a left (assignable) entity # @param scope [Object] the runtime specific scope where evaluation should take place # # @api private # def lvalue(o, scope) @@lvalue_visitor.visit_this_1(self, o, scope) end # Produces a String representation of the given object _o_ as used in interpolation. # @param o [Object] the expression of which a string representation is wanted # @param scope [Object] the runtime specific scope where evaluation should take place # # @api public # def string(o, scope) @@string_visitor.visit_this_1(self, o, scope) end # Evaluate a BlockExpression in a new scope with variables bound to the # given values. # # @param scope [Puppet::Parser::Scope] the parent scope # @param variable_bindings [Hash{String => Object}] the variable names and values to bind (names are keys, bound values are values) # @param block [Model::BlockExpression] the sequence of expressions to evaluate in the new scope # # @api private # def evaluate_block_with_bindings(scope, variable_bindings, block_expr) scope.with_guarded_scope do # change to create local scope_from - cannot give it file and line - # that is the place of the call, not "here" create_local_scope_from(variable_bindings, scope) evaluate(block_expr, scope) end end # Implementation of case option matching. # # This is the type of matching performed in a case option, using == for every type # of value except regular expression where a match is performed. # def match?(left, right) @@compare_operator.match(left, right, nil) end protected def lvalue_VariableExpression(o, scope) # evaluate the name evaluate(o.expr, scope) end # Catches all illegal lvalues # def lvalue_Object(o, scope) fail(Issues::ILLEGAL_ASSIGNMENT, o) end # An array is assignable if all entries are lvalues def lvalue_LiteralList(o, scope) o.values.map { |x| lvalue(x, scope) } end # Assign value to named variable. # The '$' sign is never part of the name. # @example In Puppet DSL # $name = value # @param name [String] name of variable without $ # @param value [Object] value to assign to the variable # @param o [Model::PopsObject] originating instruction # @param scope [Object] the runtime specific scope where evaluation should take place # @return [value<Object>] # def assign_String(name, value, o, scope) if name =~ /::/ fail(Issues::CROSS_SCOPE_ASSIGNMENT, o.left_expr, { :name => name }) end set_variable(name, value, o, scope) value end def assign_Numeric(n, value, o, scope) fail(Issues::ILLEGAL_NUMERIC_ASSIGNMENT, o.left_expr, { :varname => n.to_s }) end # Catches all illegal assignment (e.g. 1 = 2, {'a'=>1} = 2, etc) # def assign_Object(name, value, o, scope) fail(Issues::ILLEGAL_ASSIGNMENT, o) end def assign_Array(lvalues, values, o, scope) case values when Hash lvalues.map do |lval| assign(lval, values.fetch(lval) { |k| fail(Issues::MISSING_MULTI_ASSIGNMENT_KEY, o, :key => k) }, o, scope) end when Puppet::Pops::Types::PClassType if Puppet[:tasks] fail(Issues::CATALOG_OPERATION_NOT_SUPPORTED_WHEN_SCRIPTING, o, { :operation => _('multi var assignment from class') }) end # assign variables from class variables # lookup class resource and return one or more parameter values # TODO: behavior when class_name is nil resource = find_resource(scope, 'class', values.class_name) if resource base_name = "#{values.class_name.downcase}::" idx = -1 result = lvalues.map do |lval| idx += 1 varname = "#{base_name}#{lval}" if variable_exists?(varname, scope) result = get_variable_value(varname, o, scope) assign(lval, result, o, scope) else fail(Puppet::Pops::Issues::MISSING_MULTI_ASSIGNMENT_VARIABLE, o.left_expr.values[idx], { :name => varname }) end end else fail(Issues::UNKNOWN_RESOURCE, o.right_expr, { :type_name => 'Class', :title => values.class_name }) end else values = [values] unless values.is_a?(Array) if values.size != lvalues.size fail(Issues::ILLEGAL_MULTI_ASSIGNMENT_SIZE, o, :expected => lvalues.size, :actual => values.size) end lvalues.zip(values).map { |lval, val| assign(lval, val, o, scope) } end end def eval_Factory(o, scope) evaluate(o.model, scope) end # Evaluates any object not evaluated to something else to itself. def eval_Object o, scope o end # Allows nil to be used as a Nop, Evaluates to nil def eval_NilClass(o, scope) nil end # Evaluates Nop to nil. def eval_Nop(o, scope) nil end # Captures all LiteralValues not handled elsewhere. # def eval_LiteralValue(o, scope) o.value end # Reserved Words fail to evaluate # def eval_ReservedWord(o, scope) if !o.future fail(Issues::RESERVED_WORD, o, { :word => o.word }) else o.word end end def eval_LiteralDefault(o, scope) :default end def eval_LiteralUndef(o, scope) nil end # A QualifiedReference (i.e. a capitalized qualified name such as Foo, or Foo::Bar) evaluates to a PTypeType # def eval_QualifiedReference(o, scope) type = Types::TypeParser.singleton.interpret(o) fail(Issues::UNKNOWN_RESOURCE_TYPE, o, { :type_name => type.type_string }) if type.is_a?(Types::PTypeReferenceType) type end def eval_NotExpression(o, scope) !is_true?(evaluate(o.expr, scope), o.expr) end def eval_UnaryMinusExpression(o, scope) - coerce_numeric(evaluate(o.expr, scope), o, scope) end def eval_UnfoldExpression(o, scope) candidate = evaluate(o.expr, scope) case candidate when nil [] when Array candidate when Hash candidate.to_a when Puppet::Pops::Types::Iterable candidate.to_a else # turns anything else into an array (so result can be unfolded) [candidate] end end # Abstract evaluation, returns array [left, right] with the evaluated result of left_expr and # right_expr # @return <Array<Object, Object>> array with result of evaluating left and right expressions # def eval_BinaryExpression o, scope [evaluate(o.left_expr, scope), evaluate(o.right_expr, scope)] end # Evaluates assignment with operators =, +=, -= and # # @example Puppet DSL # $a = 1 # $a += 1 # $a -= 1 # def eval_AssignmentExpression(o, scope) name = lvalue(o.left_expr, scope) value = evaluate(o.right_expr, scope) if o.operator == '=' assign(name, value, o, scope) else fail(Issues::UNSUPPORTED_OPERATOR, o, { :operator => o.operator }) end value end ARITHMETIC_OPERATORS = ['+', '-', '*', '/', '%', '<<', '>>'].freeze COLLECTION_OPERATORS = ['+', '-', '<<'].freeze # Handles binary expression where lhs and rhs are array/hash or numeric and operator is +, - , *, % / << >> # def eval_ArithmeticExpression(o, scope) left = evaluate(o.left_expr, scope) right = evaluate(o.right_expr, scope) begin result = calculate(left, right, o, scope) rescue ArgumentError => e fail(Issues::RUNTIME_ERROR, o, { :detail => e.message }, e) end result end # Handles binary expression where lhs and rhs are array/hash or numeric and operator is +, - , *, % / << >> # def calculate(left, right, bin_expr, scope) operator = bin_expr.operator unless ARITHMETIC_OPERATORS.include?(operator) fail(Issues::UNSUPPORTED_OPERATOR, bin_expr, { :operator => operator }) end left_o = bin_expr.left_expr if (left.is_a?(URI) || left.is_a?(Types::PBinaryType::Binary)) && operator == '+' concatenate(left, right) elsif (left.is_a?(Array) || left.is_a?(Hash)) && COLLECTION_OPERATORS.include?(operator) # Handle operation on collections case operator when '+' concatenate(left, right) when '-' delete(left, right) when '<<' unless left.is_a?(Array) fail(Issues::OPERATOR_NOT_APPLICABLE, left_o, { :operator => operator, :left_value => left }) end left + [right] end else # Handle operation on numeric left = coerce_numeric(left, left_o, scope) right = coerce_numeric(right, bin_expr.right_expr, scope) begin if operator == '%' && (left.is_a?(Float) || right.is_a?(Float)) # Deny users the fun of seeing severe rounding errors and confusing results fail(Issues::OPERATOR_NOT_APPLICABLE, left_o, { :operator => operator, :left_value => left }) if left.is_a?(Float) fail(Issues::OPERATOR_NOT_APPLICABLE_WHEN, left_o, { :operator => operator, :left_value => left, :right_value => right }) end if right.is_a?(Time::TimeData) && !left.is_a?(Time::TimeData) if operator == '+' || operator == '*' && right.is_a?(Time::Timespan) # Switch places. Let the TimeData do the arithmetic x = left left = right right = x elsif operator == '-' && right.is_a?(Time::Timespan) left = Time::Timespan.new((left * Time::NSECS_PER_SEC).to_i) else fail(Issues::OPERATOR_NOT_APPLICABLE_WHEN, left_o, { :operator => operator, :left_value => left, :right_value => right }) end end result = left.send(operator, right) rescue NoMethodError fail(Issues::OPERATOR_NOT_APPLICABLE, left_o, { :operator => operator, :left_value => left }) rescue ZeroDivisionError fail(Issues::DIV_BY_ZERO, bin_expr.right_expr) end case result when Float if result == Float::INFINITY || result == -Float::INFINITY fail(Issues::RESULT_IS_INFINITY, left_o, { :operator => operator }) end when Integer if result < MIN_INTEGER || result > MAX_INTEGER fail(Issues::NUMERIC_OVERFLOW, bin_expr, { :value => result }) end end result end end def eval_EppExpression(o, scope) contains_sensitive = false scope["@epp"] = [] evaluate(o.body, scope) result = scope["@epp"].map do |r| if r.instance_of?(Puppet::Pops::Types::PSensitiveType::Sensitive) contains_sensitive = true string(r.unwrap, scope) else r end end.join if contains_sensitive Puppet::Pops::Types::PSensitiveType::Sensitive.new(result) else result end end def eval_RenderStringExpression(o, scope) scope["@epp"] << o.value.dup nil end def eval_RenderExpression(o, scope) result = evaluate(o.expr, scope) if result.instance_of?(Puppet::Pops::Types::PSensitiveType::Sensitive) scope["@epp"] << result else scope["@epp"] << string(result, scope) end nil end # Evaluates Puppet DSL ->, ~>, <-, and <~ def eval_RelationshipExpression(o, scope) # First level evaluation, reduction to basic data types or puppet types, the relationship operator then translates this # to the final set of references (turning strings into references, which can not naturally be done by the main evaluator since # all strings should not be turned into references. # real = eval_BinaryExpression(o, scope) @@relationship_operator.evaluate(real, o, scope) end # Evaluates x[key, key, ...] # def eval_AccessExpression(o, scope) left = evaluate(o.left_expr, scope) keys = o.keys || [] if left.is_a?(Types::PClassType) # Evaluate qualified references without errors no undefined types keys = keys.map { |key| key.is_a?(Model::QualifiedReference) ? Types::TypeParser.singleton.interpret(key) : evaluate(key, scope) } else keys = keys.map { |key| evaluate(key, scope) } # Resource[File] becomes File return keys[0] if Types::PResourceType::DEFAULT == left && keys.size == 1 && keys[0].is_a?(Types::PResourceType) end AccessOperator.new(o).access(left, scope, *keys) end # Evaluates <, <=, >, >=, and == # def eval_ComparisonExpression o, scope left = evaluate(o.left_expr, scope) right = evaluate(o.right_expr, scope) begin # Left is a type if left.is_a?(Types::PAnyType) case o.operator when '==' @@type_calculator.equals(left, right) when '!=' !@@type_calculator.equals(left, right) when '<' # left can be assigned to right, but they are not equal @@type_calculator.assignable?(right, left) && !@@type_calculator.equals(left, right) when '<=' # left can be assigned to right @@type_calculator.assignable?(right, left) when '>' # right can be assigned to left, but they are not equal @@type_calculator.assignable?(left, right) && !@@type_calculator.equals(left, right) when '>=' # right can be assigned to left @@type_calculator.assignable?(left, right) else fail(Issues::UNSUPPORTED_OPERATOR, o, { :operator => o.operator }) end else case o.operator when '==' @@compare_operator.equals(left, right) when '!=' !@@compare_operator.equals(left, right) when '<' @@compare_operator.compare(left, right) < 0 when '<=' @@compare_operator.compare(left, right) <= 0 when '>' @@compare_operator.compare(left, right) > 0 when '>=' @@compare_operator.compare(left, right) >= 0 else fail(Issues::UNSUPPORTED_OPERATOR, o, { :operator => o.operator }) end end rescue ArgumentError => e fail(Issues::COMPARISON_NOT_POSSIBLE, o, { :operator => o.operator, :left_value => left, :right_value => right, :detail => e.message }, e) end end # Evaluates matching expressions with type, string or regexp rhs expression. # If RHS is a type, the =~ matches compatible (instance? of) type. # # @example # x =~ /abc.*/ # @example # x =~ "abc.*/" # @example # y = "abc" # x =~ "${y}.*" # @example # [1,2,3] =~ Array[Integer[1,10]] # # Note that a string is not instance? of Regexp, only Regular expressions are. # The Pattern type should instead be used as it is specified as subtype of String. # # @return [Boolean] if a match was made or not. Also sets $0..$n to matchdata in current scope. # def eval_MatchExpression o, scope left = evaluate(o.left_expr, scope) pattern = evaluate(o.right_expr, scope) # matches RHS types as instance of for all types except a parameterized Regexp[R] if pattern.is_a?(Types::PAnyType) # evaluate as instance? of type check matched = pattern.instance?(left) # convert match result to Boolean true, or false return o.operator == '=~' ? !!matched : !matched end if pattern.is_a?(SemanticPuppet::VersionRange) # evaluate if range includes version matched = Types::PSemVerRangeType.include?(pattern, left) return o.operator == '=~' ? matched : !matched end begin pattern = Regexp.new(pattern) unless pattern.is_a?(Regexp) rescue StandardError => e fail(Issues::MATCH_NOT_REGEXP, o.right_expr, { :detail => e.message }, e) end unless left.is_a?(String) fail(Issues::MATCH_NOT_STRING, o.left_expr, { :left_value => left }) end matched = pattern.match(left) # nil, or MatchData set_match_data(matched, scope) # creates ephemeral # convert match result to Boolean true, or false o.operator == '=~' ? !!matched : !matched end # Evaluates Puppet DSL `in` expression # def eval_InExpression o, scope left = evaluate(o.left_expr, scope) right = evaluate(o.right_expr, scope) @@compare_operator.include?(right, left, scope) end # @example # $a and $b # b is only evaluated if a is true # def eval_AndExpression o, scope is_true?(evaluate(o.left_expr, scope), o.left_expr) ? is_true?(evaluate(o.right_expr, scope), o.right_expr) : false end # @example # a or b # b is only evaluated if a is false # def eval_OrExpression o, scope is_true?(evaluate(o.left_expr, scope), o.left_expr) ? true : is_true?(evaluate(o.right_expr, scope), o.right_expr) end # Evaluates each entry of the literal list and creates a new Array # Supports unfolding of entries # @return [Array] with the evaluated content # def eval_LiteralList o, scope unfold([], o.values, scope) end # Evaluates each entry of the literal hash and creates a new Hash. # @return [Hash] with the evaluated content # def eval_LiteralHash o, scope # optimized o.entries.each_with_object({}) { |entry, h| h[evaluate(entry.key, scope)] = evaluate(entry.value, scope); } end # Evaluates all statements and produces the last evaluated value # def eval_BlockExpression o, scope o.statements.reduce(nil) { |_memo, s| evaluate(s, scope) } end # Performs optimized search over case option values, lazily evaluating each # until there is a match. If no match is found, the case expression's default expression # is evaluated (it may be nil or Nop if there is no default, thus producing nil). # If an option matches, the result of evaluating that option is returned. # @return [Object, nil] what a matched option returns, or nil if nothing matched. # def eval_CaseExpression(o, scope) # memo scope level before evaluating test - don't want a match in the case test to leak $n match vars # to expressions after the case expression. # scope.with_guarded_scope do test = evaluate(o.test, scope) result = nil the_default = nil if o.options.find do |co| # the first case option that matches next unless co.values.find do |c| c = unwind_parentheses(c) case c when Model::LiteralDefault the_default = co.then_expr next false when Model::UnfoldExpression # not ideal for error reporting, since it is not known which unfolded result # that caused an error - the entire unfold expression is blamed (i.e. the var c, passed to is_match?) evaluate(c, scope).any? { |v| is_match?(test, v, c, co, scope) } else is_match?(test, evaluate(c, scope), c, co, scope) end end result = evaluate(co.then_expr, scope) true # the option was picked end result # an option was picked, and produced a result else evaluate(the_default, scope) # evaluate the default (should be a nop/nil) if there is no default). end end end # Evaluates a CollectExpression by creating a collector transformer. The transformer # will evaluate the collection, create the appropriate collector, and hand it off # to the compiler to collect the resources specified by the query. # def eval_CollectExpression o, scope if o.query.is_a?(Model::ExportedQuery) optionally_fail(Issues::RT_NO_STORECONFIGS, o); end CollectorTransformer.new().transform(o, scope) end def eval_ParenthesizedExpression(o, scope) evaluate(o.expr, scope) end # This evaluates classes, nodes and resource type definitions to nil, since 3x: # instantiates them, and evaluates their parameters and body. This is achieved by # providing bridge AST classes in Puppet::Parser::AST::PopsBridge that bridges a # Pops Program and a Pops Expression. # # Since all Definitions are handled "out of band", they are treated as a no-op when # evaluated. # def eval_Definition(o, scope) nil end def eval_Program(o, scope) file = o.locator.file line = 0 # Add stack frame for "top scope" logic. See Puppet::Pops::PuppetStack Puppet::Pops::PuppetStack.stack(file, line, self, 'evaluate', [o.body, scope]) # evaluate(o.body, scope) rescue Puppet::Pops::Evaluator::PuppetStopIteration => ex # breaking out of a file level program is not allowed # TRANSLATOR break() is a method that should not be translated raise Puppet::ParseError.new(_("break() from context where this is illegal"), ex.file, ex.line) end # Produces Array[PAnyType], an array of resource references # def eval_ResourceExpression(o, scope) exported = o.exported virtual = o.virtual # Get the type name type_name = if (tmp_name = o.type_name).is_a?(Model::QualifiedName) tmp_name.value # already validated as a name else type_name_acceptable = case o.type_name when Model::QualifiedReference true when Model::AccessExpression o.type_name.left_expr.is_a?(Model::QualifiedReference) end evaluated_name = evaluate(tmp_name, scope) unless type_name_acceptable actual = type_calculator.generalize(type_calculator.infer(evaluated_name)).to_s fail(Issues::ILLEGAL_RESOURCE_TYPE, o.type_name, { :actual => actual }) end # must be a CatalogEntry subtype case evaluated_name when Types::PClassType unless evaluated_name.class_name.nil? fail(Issues::ILLEGAL_RESOURCE_TYPE, o.type_name, { :actual => evaluated_name.to_s }) end 'class' when Types::PResourceType unless evaluated_name.title().nil? fail(Issues::ILLEGAL_RESOURCE_TYPE, o.type_name, { :actual => evaluated_name.to_s }) end evaluated_name.type_name # assume validated when Types::PTypeReferenceType fail(Issues::UNKNOWN_RESOURCE_TYPE, o.type_string, { :type_name => evaluated_name.to_s }) else actual = type_calculator.generalize(type_calculator.infer(evaluated_name)).to_s fail(Issues::ILLEGAL_RESOURCE_TYPE, o.type_name, { :actual => actual }) end end # This is a runtime check - the model is valid, but will have runtime issues when evaluated # and storeconfigs is not set. if o.exported optionally_fail(Issues::RT_NO_STORECONFIGS_EXPORT, o); end titles_to_body = {} body_to_titles = {} body_to_params = {} # titles are evaluated before attribute operations o.bodies.map do |body| titles = evaluate(body.title, scope) # Title may not be nil # Titles may be given as an array, it is ok if it is empty, but not if it contains nil entries # Titles may not be an empty String # Titles must be unique in the same resource expression # There may be a :default entry, its entries apply with lower precedence # if titles.nil? fail(Issues::MISSING_TITLE, body.title) end titles = [titles].flatten # Check types of evaluated titles and duplicate entries titles.each_with_index do |title, index| if title.nil? fail(Issues::MISSING_TITLE_AT, body.title, { :index => index }) elsif !title.is_a?(String) && title != :default actual = type_calculator.generalize(type_calculator.infer(title)).to_s fail(Issues::ILLEGAL_TITLE_TYPE_AT, body.title, { :index => index, :actual => actual }) elsif title == EMPTY_STRING fail(Issues::EMPTY_STRING_TITLE_AT, body.title, { :index => index }) elsif titles_to_body[title] fail(Issues::DUPLICATE_TITLE, o, { :title => title }) end titles_to_body[title] = body end # Do not create a real instance from the :default case titles.delete(:default) body_to_titles[body] = titles # Store evaluated parameters in a hash associated with the body, but do not yet create resource # since the entry containing :defaults may appear later body_to_params[body] = body.operations.each_with_object({}) do |op, param_memo| params = evaluate(op, scope) params = [params] unless params.is_a?(Array) params.each do |p| if param_memo.include? p.name fail(Issues::DUPLICATE_ATTRIBUTE, o, { :attribute => p.name }) end param_memo[p.name] = p end end end # Titles and Operations have now been evaluated and resources can be created # Each production is a PResource, and an array of all is produced as the result of # evaluating the ResourceExpression. # defaults_hash = body_to_params[titles_to_body[:default]] || {} o.bodies.map do |body| titles = body_to_titles[body] params = defaults_hash.merge(body_to_params[body] || {}) create_resources(o, scope, virtual, exported, type_name, titles, params.values) end.flatten.compact end def eval_ResourceOverrideExpression(o, scope) evaluated_resources = evaluate(o.resources, scope) evaluated_parameters = o.operations.map { |op| evaluate(op, scope) } create_resource_overrides(o, scope, [evaluated_resources].flatten, evaluated_parameters) evaluated_resources end def eval_ApplyExpression(o, scope) # All expressions are wrapped in an ApplyBlockExpression so we can identify the contents of # that block. However we don't want to serialize the block expression, so unwrap here. body = if o.body.statements.count == 1 o.body.statements[0] else Model::BlockExpression.from_asserted_hash(o.body._pcore_init_hash) end Puppet.lookup(:apply_executor).apply(unfold([], o.arguments, scope), body, scope) end # Produces 3x parameter def eval_AttributeOperation(o, scope) create_resource_parameter(o, scope, o.attribute_name, evaluate(o.value_expr, scope), o.operator) end def eval_AttributesOperation(o, scope) hashed_params = evaluate(o.expr, scope) unless hashed_params.is_a?(Hash) actual = type_calculator.generalize(type_calculator.infer(hashed_params)).to_s fail(Issues::TYPE_MISMATCH, o.expr, { :expected => 'Hash', :actual => actual }) end hashed_params.map { |k, v| create_resource_parameter(o, scope, k, v, '=>') } end # Sets default parameter values for a type, produces the type # def eval_ResourceDefaultsExpression(o, scope) type = evaluate(o.type_ref, scope) type_name = if type.is_a?(Types::PResourceType) && !type.type_name.nil? && type.title.nil? type.type_name # assume it is a valid name else actual = type_calculator.generalize(type_calculator.infer(type)) fail(Issues::ILLEGAL_RESOURCE_TYPE, o.type_ref, { :actual => actual }) end evaluated_parameters = o.operations.map { |op| evaluate(op, scope) } create_resource_defaults(o, scope, type_name, evaluated_parameters) # Produce the type type end # Evaluates function call by name. #
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/runtime3_support.rb
lib/puppet/pops/evaluator/runtime3_support.rb
# frozen_string_literal: true module Puppet::Pops module Evaluator # A module with bindings between the new evaluator and the 3x runtime. # The intention is to separate all calls into scope, compiler, resource, etc. in this module # to make it easier to later refactor the evaluator for better implementations of the 3x classes. # # @api private module Runtime3Support NAME_SPACE_SEPARATOR = '::' # Fails the evaluation of _semantic_ with a given issue. # # @param issue [Issue] the issue to report # @param semantic [ModelPopsObject] the object for which evaluation failed in some way. Used to determine origin. # @param options [Hash] hash of optional named data elements for the given issue # @return [!] this method does not return # @raise [Puppet::ParseError] an evaluation error initialized from the arguments (TODO: Change to EvaluationError?) # def fail(issue, semantic, options = {}, except = nil) optionally_fail(issue, semantic, options, except) # an error should have been raised since fail always fails raise ArgumentError, _("Internal Error: Configuration of runtime error handling wrong: should have raised exception") end # Optionally (based on severity) Fails the evaluation of _semantic_ with a given issue # If the given issue is configured to be of severity < :error it is only reported, and the function returns. # # @param issue [Issue] the issue to report # @param semantic [ModelPopsObject] the object for which evaluation failed in some way. Used to determine origin. # @param options [Hash] hash of optional named data elements for the given issue # @return [!] this method does not return # @raise [Puppet::ParseError] an evaluation error initialized from the arguments (TODO: Change to EvaluationError?) # def optionally_fail(issue, semantic, options = {}, except = nil) if except.nil? && diagnostic_producer.severity_producer[issue] == :error # Want a stacktrace, and it must be passed as an exception begin raise EvaluationError rescue EvaluationError => e except = e end end diagnostic_producer.accept(issue, semantic, options, except) end # Optionally (based on severity) Fails the evaluation with a given issue # If the given issue is configured to be of severity < :error it is only reported, and the function returns. # The location the issue is reported against is found is based on the top file/line in the puppet call stack # # @param issue [Issue] the issue to report # @param options [Hash] hash of optional named data elements for the given issue # @return [!] this method may not return, nil if it does # @raise [Puppet::ParseError] an evaluation error initialized from the arguments # def runtime_issue(issue, options = {}) # Get position from puppet runtime stack file, line = Puppet::Pops::PuppetStack.top_of_stack # Use a SemanticError as the sourcepos semantic = Puppet::Pops::SemanticError.new(issue, nil, options.merge({ :file => file, :line => line })) optionally_fail(issue, semantic) nil end # Binds the given variable name to the given value in the given scope. # The reference object `o` is intended to be used for origin information - the 3x scope implementation # only makes use of location when there is an error. This is now handled by other mechanisms; first a check # is made if a variable exists and an error is raised if attempting to change an immutable value. Errors # in name, numeric variable assignment etc. have also been validated prior to this call. In the event the # scope.setvar still raises an error, the general exception handling for evaluation of the assignment # expression knows about its location. Because of this, there is no need to extract the location for each # setting (extraction is somewhat expensive since 3x requires line instead of offset). # def set_variable(name, value, o, scope) # Scope also checks this but requires that location information are passed as options. # Those are expensive to calculate and a test is instead made here to enable failing with better information. # The error is not specific enough to allow catching it - need to check the actual message text. # TODO: Improve the messy implementation in Scope. # if name == "server_facts" fail(Issues::ILLEGAL_RESERVED_ASSIGNMENT, o, { :name => name }) end if scope.bound?(name) if Puppet::Parser::Scope::RESERVED_VARIABLE_NAMES.include?(name) fail(Issues::ILLEGAL_RESERVED_ASSIGNMENT, o, { :name => name }) else fail(Issues::ILLEGAL_REASSIGNMENT, o, { :name => name }) end end scope.setvar(name, value) end # Returns the value of the variable (nil is returned if variable has no value, or if variable does not exist) # def get_variable_value(name, o, scope) # Puppet 3x stores all variables as strings (then converts them back to numeric with a regexp... to see if it is a match variable) # Not ideal, scope should support numeric lookup directly instead. # TODO: consider fixing scope catch(:undefined_variable) { x = scope.lookupvar(name.to_s) # Must convert :undef back to nil - this can happen when an undefined variable is used in a # parameter's default value expression - there nil must be :undef to work with the rest of 3x. # Now that the value comes back to 4x it is changed to nil. return :undef.equal?(x) ? nil : x } # It is always ok to reference numeric variables even if they are not assigned. They are always undef # if not set by a match expression. # unless name =~ Puppet::Pops::Patterns::NUMERIC_VAR_NAME optionally_fail(Puppet::Pops::Issues::UNKNOWN_VARIABLE, o, { :name => name }) end nil # in case unknown variable is configured as a warning or ignore end # Returns true if the variable of the given name is set in the given most nested scope. True is returned even if # variable is bound to nil. # def variable_bound?(name, scope) scope.bound?(name.to_s) end # Returns true if the variable is bound to a value or nil, in the scope or it's parent scopes. # def variable_exists?(name, scope) scope.exist?(name.to_s) end def set_match_data(match_data, scope) # See set_variable for rationale for not passing file and line to ephemeral_from. # NOTE: The 3x scope adds one ephemeral(match) to its internal stack per match that succeeds ! It never # clears anything. Thus a context that performs many matches will get very deep (there simply is no way to # clear the match variables without rolling back the ephemeral stack.) # This implementation does not attempt to fix this, it behaves the same bad way. unless match_data.nil? scope.ephemeral_from(match_data) end end # Creates a local scope with vairalbes set from a hash of variable name to value # def create_local_scope_from(hash, scope) # two dummy values are needed since the scope tries to give an error message (can not happen in this # case - it is just wrong, the error should be reported by the caller who knows in more detail where it # is in the source. # raise ArgumentError, _("Internal error - attempt to create a local scope without a hash") unless hash.is_a?(Hash) scope.ephemeral_from(hash) end # Creates a nested match scope def create_match_scope_from(scope) # Create a transparent match scope (for future matches) scope.new_match_scope(nil) end def get_scope_nesting_level(scope) scope.ephemeral_level end def set_scope_nesting_level(scope, level) # 3x uses this method to reset the level, scope.pop_ephemerals(level) end # Adds a relationship between the given `source` and `target` of the given `relationship_type` # @param source [Puppet:Pops::Types::PCatalogEntryType] the source end of the relationship (from) # @param target [Puppet:Pops::Types::PCatalogEntryType] the target end of the relationship (to) # @param relationship_type [:relationship, :subscription] the type of the relationship # def add_relationship(source, target, relationship_type, scope) # The 3x way is to record a Puppet::Parser::Relationship that is evaluated at the end of the compilation. # This means it is not possible to detect any duplicates at this point (and signal where an attempt is made to # add a duplicate. There is also no location information to signal the original place in the logic. The user will have # to go fish. # The 3.x implementation is based on Strings :-o, so the source and target must be transformed. The resolution is # done by Catalog#resource(type, title). To do that, it creates a Puppet::Resource since it is responsible for # translating the name/type/title and create index-keys used by the catalog. The Puppet::Resource has bizarre parsing of # the type and title (scan for [] that is interpreted as type/title (but it gets it wrong). # Moreover if the type is "" or "component", the type is Class, and if the type is :main, it is :main, all other cases # undergo capitalization of name-segments (foo::bar becomes Foo::Bar). (This was earlier done in the reverse by the parser). # Further, the title undergoes the same munging !!! # # That bug infested nest of messy logic needs serious Exorcism! # # Unfortunately it is not easy to simply call more intelligent methods at a lower level as the compiler evaluates the recorded # Relationship object at a much later point, and it is responsible for invoking all the messy logic. # # TODO: Revisit the below logic when there is a sane implementation of the catalog, compiler and resource. For now # concentrate on transforming the type references to what is expected by the wacky logic. # # HOWEVER, the Compiler only records the Relationships, and the only method it calls is @relationships.each{|x| x.evaluate(catalog) } # Which means a smarter Relationship class could do this right. Instead of obtaining the resource from the catalog using # the borked resource(type, title) which creates a resource for the purpose of looking it up, it needs to instead # scan the catalog's resources # # GAAAH, it is even worse! # It starts in the parser, which parses "File['foo']" into an AST::ResourceReference with type = File, and title = foo # This AST is evaluated by looking up the type/title in the scope - causing it to be loaded if it exists, and if not, the given # type name/title is used. It does not search for resource instances, only classes and types. It returns symbolic information # [type, [title, title]]. From this, instances of Puppet::Resource are created and returned. These only have type/title information # filled out. One or an array of resources are returned. # This set of evaluated (empty reference) Resource instances are then passed to the relationship operator. It creates a # Puppet::Parser::Relationship giving it a source and a target that are (empty reference) Resource instances. These are then remembered # until the relationship is evaluated by the compiler (at the end). When evaluation takes place, the (empty reference) Resource instances # are converted to String (!?! WTF) on the simple format "#{type}[#{title}]", and the catalog is told to find a resource, by giving # it this string. If it cannot find the resource it fails, else the before/notify parameter is appended with the target. # The search for the resource begin with (you guessed it) again creating an (empty reference) resource from type and title (WTF?!?!). # The catalog now uses the reference resource to compute a key [r.type, r.title.to_s] and also gets a uniqueness key from the # resource (This is only a reference type created from title and type). If it cannot find it with the first key, it uses the # uniqueness key to lookup. # # This is probably done to allow a resource type to munge/translate the title in some way (but it is quite unclear from the long # and convoluted path of evaluation. # In order to do this in a way that is similar to 3.x two resources are created to be used as keys. # # And if that is not enough, a source/target may be a Collector (a baked query that will be evaluated by the # compiler - it is simply passed through here for processing by the compiler at the right time). # if source.is_a?(Collectors::AbstractCollector) # use verbatim - behavior defined by 3x source_resource = source else # transform into the wonderful String representation in 3x type, title = Runtime3Converter.instance.catalog_type_to_split_type_title(source) type = Runtime3ResourceSupport.find_resource_type(scope, type) unless type == 'class' || type == 'node' source_resource = Puppet::Resource.new(type, title) end if target.is_a?(Collectors::AbstractCollector) # use verbatim - behavior defined by 3x target_resource = target else # transform into the wonderful String representation in 3x type, title = Runtime3Converter.instance.catalog_type_to_split_type_title(target) type = Runtime3ResourceSupport.find_resource_type(scope, type) unless type == 'class' || type == 'node' target_resource = Puppet::Resource.new(type, title) end # Add the relationship to the compiler for later evaluation. scope.compiler.add_relationship(Puppet::Parser::Relationship.new(source_resource, target_resource, relationship_type)) end # Coerce value `v` to numeric or fails. # The given value `v` is coerced to Numeric, and if that fails the operation # calls {#fail}. # @param v [Object] the value to convert # @param o [Object] originating instruction # @param scope [Object] the (runtime specific) scope where evaluation of o takes place # @return [Numeric] value `v` converted to Numeric. # def coerce_numeric(v, o, scope) if v.is_a?(Numeric) return v end n = Utils.to_n(v) unless n fail(Issues::NOT_NUMERIC, o, { :value => v }) end # this point is reached if there was a conversion optionally_fail(Issues::NUMERIC_COERCION, o, { :before => v, :after => n }) n end # Provides the ability to call a 3.x or 4.x function from the perspective of a 3.x function or ERB template. # The arguments to the function must be an Array containing values compliant with the 4.x calling convention. # If the targeted function is a 3.x function, the values will be transformed. # @param name [String] the name of the function (without the 'function_' prefix used by scope) # @param args [Array] arguments, may be empty # @param scope [Object] the (runtime specific) scope where evaluation takes place # @raise [ArgumentError] 'unknown function' if the function does not exist # def external_call_function(name, args, scope, &block) # Call via 4x API if the function exists there loaders = scope.compiler.loaders # Since this is a call from non puppet code, it is not possible to relate it to a module loader # It is known where the call originates by using the scope associated module - but this is the calling scope # and it does not defined the visibility of functions from a ruby function's perspective. Instead, # this is done from the perspective of the environment. loader = loaders.private_environment_loader func = loader.load(:function, name) if loader if func Puppet::Util::Profiler.profile(name, [:functions, name]) do return func.call(scope, *args, &block) end end # Call via 3x API if function exists there raise ArgumentError, _("Unknown function '%{name}'") % { name: name } unless Puppet::Parser::Functions.function(name) # 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 mapped_args = Runtime3FunctionArgumentConverter.map_args(args, scope, '') result = scope.send("function_#{name}", mapped_args, &block) # Prevent non r-value functions from leaking their result (they are not written to care about this) Puppet::Parser::Functions.rvalue?(name) ? result : nil end def call_function(name, args, o, scope, &block) file, line = extract_file_line(o) loader = Adapters::LoaderAdapter.loader_for_model_object(o, file) func = loader.load(:function, name) if loader if func Puppet::Util::Profiler.profile(name, [:functions, name]) do # Add stack frame when calling. return Puppet::Pops::PuppetStack.stack(file || '', line, func, :call, [scope, *args], &block) end end # Call via 3x API if function exists there without having been autoloaded fail(Issues::UNKNOWN_FUNCTION, o, { :name => name }) unless Puppet::Parser::Functions.function(name) # 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 mapped_args = Runtime3FunctionArgumentConverter.map_args(args, scope, '') # The 3x function performs return value mapping and returns nil if it is not of rvalue type Puppet::Pops::PuppetStack.stack(file, line, scope, "function_#{name}", [mapped_args], &block) end # The o is used for source reference def create_resource_parameter(o, scope, name, value, operator) file, line = extract_file_line(o) Puppet::Parser::Resource::Param.new( :name => name, :value => convert(value, scope, nil), # converted to 3x since 4x supports additional objects / types :source => scope.source, :line => line, :file => file, :add => operator == '+>' ) end def convert(value, scope, undef_value) Runtime3Converter.instance.convert(value, scope, undef_value) end def create_resources(o, scope, virtual, exported, type_name, resource_titles, evaluated_parameters) # Not 100% accurate as this is the resource expression location and each title is processed separately # The titles are however the result of evaluation and they have no location at this point (an array # of positions for the source expressions are required for this to work). # TODO: Revisit and possible improve the accuracy. # file, line = extract_file_line(o) Runtime3ResourceSupport.create_resources(file, line, scope, virtual, exported, type_name, resource_titles, evaluated_parameters) end # Defines default parameters for a type with the given name. # def create_resource_defaults(o, scope, type_name, evaluated_parameters) # Note that name must be capitalized in this 3x call # The 3x impl creates a Resource instance with a bogus title and then asks the created resource # for the type of the name. # Note, locations are available per parameter. # scope.define_settings(capitalize_qualified_name(type_name), evaluated_parameters.flatten) end # Capitalizes each segment of a qualified name # def capitalize_qualified_name(name) name.split(/::/).map(&:capitalize).join(NAME_SPACE_SEPARATOR) end # Creates resource overrides for all resource type objects in evaluated_resources. The same set of # evaluated parameters are applied to all. # def create_resource_overrides(o, scope, evaluated_resources, evaluated_parameters) # Not 100% accurate as this is the resource expression location and each title is processed separately # The titles are however the result of evaluation and they have no location at this point (an array # of positions for the source expressions are required for this to work. # TODO: Revisit and possible improve the accuracy. # file, line = extract_file_line(o) # A *=> results in an array of arrays evaluated_parameters = evaluated_parameters.flatten evaluated_resources.each do |r| unless r.is_a?(Types::PResourceType) && r.type_name != 'class' fail(Issues::ILLEGAL_OVERRIDDEN_TYPE, o, { :actual => r }) end t = Runtime3ResourceSupport.find_resource_type(scope, r.type_name) resource = Puppet::Parser::Resource.new( t, r.title, { :parameters => evaluated_parameters, :file => file, :line => line, # WTF is this? Which source is this? The file? The name of the context ? :source => scope.source, :scope => scope }, false # defaults should not override ) scope.compiler.add_override(resource) end end # Finds a resource given a type and a title. # def find_resource(scope, type_name, title) scope.compiler.findresource(type_name, title) end # Returns the value of a resource's parameter by first looking up the parameter in the resource # and then in the defaults for the resource. Since the resource exists (it must in order to look up its # parameters, any overrides have already been applied). Defaults are not applied to a resource until it # has been finished (which typically has not taken place when this is evaluated; hence the dual lookup). # def get_resource_parameter_value(scope, resource, parameter_name) # This gets the parameter value, or nil (for both valid parameters and parameters that do not exist). val = resource[parameter_name] # Sometimes the resource is a Puppet::Parser::Resource and sometimes it is # a Puppet::Resource. The Puppet::Resource case occurs when puppet language # is evaluated against an already completed catalog (where all instances of # Puppet::Parser::Resource are converted to Puppet::Resource instances). # Evaluating against an already completed catalog is really only found in # the language specification tests, where the puppet language is used to # test itself. if resource.is_a?(Puppet::Parser::Resource) # The defaults must be looked up in the scope where the resource was created (not in the given # scope where the lookup takes place. resource_scope = resource.scope defaults = resource_scope.lookupdefaults(resource.type) if val.nil? && resource_scope if defaults # NOTE: 3x resource keeps defaults as hash using symbol for name as key to Parameter which (again) holds # name and value. # NOTE: meta parameters that are unset ends up here, and there are no defaults for those encoded # in the defaults, they may receive hardcoded defaults later (e.g. 'tag'). param = defaults[parameter_name.to_sym] # Some parameters (meta parameters like 'tag') does not return a param from which the value can be obtained # at all times. Instead, they return a nil param until a value has been set. val = param.nil? ? nil : param.value end end val end # Returns true, if the given name is the name of a resource parameter. # def is_parameter_of_resource?(scope, resource, name) return false unless name.is_a?(String) resource.valid_parameter?(name) end # This is the same type of "truth" as used in the current Puppet DSL. # def is_true?(value, o) # Is the value true? This allows us to control the definition of truth # in one place. case value # Support :undef since it may come from a 3x structure when :undef false when String true else !!value end end def extract_file_line(o) o.is_a?(Model::Positioned) ? [o.file, o.line] : [nil, -1] end # Creates a diagnostic producer def diagnostic_producer Validation::DiagnosticProducer.new( ExceptionRaisingAcceptor.new(), # Raises exception on all issues SeverityProducer.new(), # All issues are errors Model::ModelLabelProvider.new() ) end # Configure the severity of failures class SeverityProducer < Validation::SeverityProducer def initialize super p = self # Issues triggering warning only if --debug is on if Puppet[:debug] p[Issues::EMPTY_RESOURCE_SPECIALIZATION] = :warning else p[Issues::EMPTY_RESOURCE_SPECIALIZATION] = :ignore end # if strict variables are on, an error is raised # if strict variables are off, the Puppet[strict] defines what is done # if Puppet[:strict_variables] p[Issues::UNKNOWN_VARIABLE] = :error elsif Puppet[:strict] == :off p[Issues::UNKNOWN_VARIABLE] = :ignore else p[Issues::UNKNOWN_VARIABLE] = Puppet[:strict] end # Store config issues, ignore or warning p[Issues::RT_NO_STORECONFIGS_EXPORT] = Puppet[:storeconfigs] ? :ignore : :warning p[Issues::RT_NO_STORECONFIGS] = Puppet[:storeconfigs] ? :ignore : :warning p[Issues::CLASS_NOT_VIRTUALIZABLE] = :error p[Issues::NUMERIC_COERCION] = Puppet[:strict] == :off ? :ignore : Puppet[:strict] p[Issues::SERIALIZATION_DEFAULT_CONVERTED_TO_STRING] = Puppet[:strict] == :off ? :warning : Puppet[:strict] p[Issues::SERIALIZATION_UNKNOWN_CONVERTED_TO_STRING] = Puppet[:strict] == :off ? :warning : Puppet[:strict] p[Issues::SERIALIZATION_UNKNOWN_KEY_CONVERTED_TO_STRING] = Puppet[:strict] == :off ? :warning : Puppet[:strict] end end # An acceptor of diagnostics that immediately raises an exception. class ExceptionRaisingAcceptor < Validation::Acceptor def accept(diagnostic) super IssueReporter.assert_and_report(self, { :message => "Evaluation Error:", :emit_warnings => true, # log warnings :exception_class => Puppet::PreformattedError }) if errors? raise ArgumentError, _("Internal Error: Configuration of runtime error handling wrong: should have raised exception") end end end class EvaluationError < StandardError end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/epp_evaluator.rb
lib/puppet/pops/evaluator/epp_evaluator.rb
# frozen_string_literal: true # Handler of Epp call/evaluation from the epp and inline_epp functions # class Puppet::Pops::Evaluator::EppEvaluator def self.inline_epp(scope, epp_source, template_args = nil) unless epp_source.is_a?(String) # TRANSLATORS 'inline_epp()' is a method name and 'epp' refers to 'Embedded Puppet (EPP) template' and should not be translated raise ArgumentError, _("inline_epp(): the first argument must be a String with the epp source text, got a %{class_name}") % { class_name: epp_source.class } end # Parse and validate the source parser = Puppet::Pops::Parser::EvaluatingParser::EvaluatingEppParser.new begin result = parser.parse_string(epp_source, 'inlined-epp-text') rescue Puppet::ParseError => e # TRANSLATORS 'inline_epp()' is a method name and 'EPP' refers to 'Embedded Puppet (EPP) template' and should not be translated raise ArgumentError, _("inline_epp(): Invalid EPP: %{detail}") % { detail: e.message } end # Evaluate (and check template_args) evaluate(parser, 'inline_epp', scope, false, result, template_args) end def self.epp(scope, file, env_name, template_args = nil) unless file.is_a?(String) # TRANSLATORS 'epp()' is a method name and should not be translated raise ArgumentError, _("epp(): the first argument must be a String with the filename, got a %{class_name}") % { class_name: file.class } end unless Puppet::FileSystem.exist?(file) unless file =~ /\.epp$/ file += ".epp" end end scope.debug "Retrieving epp template #{file}" template_file = Puppet::Parser::Files.find_template(file, env_name) if template_file.nil? || !Puppet::FileSystem.exist?(template_file) raise Puppet::ParseError, _("Could not find template '%{file}'") % { file: file } end # Parse and validate the source parser = Puppet::Pops::Parser::EvaluatingParser::EvaluatingEppParser.new begin result = parser.parse_file(template_file) rescue Puppet::ParseError => e # TRANSLATORS 'epp()' is a method name and 'EPP' refers to 'Embedded Puppet (EPP) template' and should not be translated raise ArgumentError, _("epp(): Invalid EPP: %{detail}") % { detail: e.message } end # Evaluate (and check template_args) evaluate(parser, 'epp', scope, true, result, template_args) end def self.evaluate(parser, func_name, scope, use_global_scope_only, parse_result, template_args) template_args, template_args_set = handle_template_args(func_name, template_args) body = parse_result.body unless body.is_a?(Puppet::Pops::Model::LambdaExpression) # TRANSLATORS 'LambdaExpression' is a class name and should not be translated raise ArgumentError, _("%{function_name}(): the parser did not produce a LambdaExpression, got '%{class_name}'") % { function_name: func_name, class_name: body.class } end unless body.body.is_a?(Puppet::Pops::Model::EppExpression) # TRANSLATORS 'EppExpression' is a class name and should not be translated raise ArgumentError, _("%{function_name}(): the parser did not produce an EppExpression, got '%{class_name}'") % { function_name: func_name, class_name: body.body.class } end unless parse_result.definitions.empty? # TRANSLATORS 'EPP' refers to 'Embedded Puppet (EPP) template' raise ArgumentError, _("%{function_name}(): The EPP template contains illegal expressions (definitions)") % { function_name: func_name } end parameters_specified = body.body.parameters_specified if parameters_specified || template_args_set enforce_parameters = parameters_specified else enforce_parameters = true end # filter out all qualified names and set them in qualified_variables # only pass unqualified (filtered) variable names to the template filtered_args = {} template_args.each_pair do |k, v| if k =~ /::/ k = k[2..] if k.start_with?('::') scope[k] = v else filtered_args[k] = v end end template_args = filtered_args # inline_epp() logic sees all local variables, epp() all global if use_global_scope_only scope.with_global_scope do |global_scope| parser.closure(body, global_scope).call_by_name(template_args, enforce_parameters) end else parser.closure(body, scope).call_by_name(template_args, enforce_parameters) end end private_class_method :evaluate def self.handle_template_args(func_name, template_args) if template_args.nil? [{}, false] else unless template_args.is_a?(Hash) # TRANSLATORS 'template_args' is a variable name and should not be translated raise ArgumentError, _("%{function_name}(): the template_args must be a Hash, got a %{class_name}") % { function_name: func_name, class_name: template_args.class } end [template_args, true] end end private_class_method :handle_template_args end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/json_strict_literal_evaluator.rb
lib/puppet/pops/evaluator/json_strict_literal_evaluator.rb
# frozen_string_literal: true # Literal values for # # * String # * Numbers # * Booleans # * Undef (produces nil) # * Array # * Hash where keys must be Strings # * QualifiedName # # Not considered literal: # # * QualifiedReference # i.e. File, FooBar # * Default is not accepted as being literal # * Regular Expression is not accepted as being literal # * Hash with non String keys # * String with interpolation # class Puppet::Pops::Evaluator::JsonStrictLiteralEvaluator # include Puppet::Pops::Utils COMMA_SEPARATOR = ', ' def initialize @@literal_visitor ||= Puppet::Pops::Visitor.new(self, "literal", 0, 0) end def literal(ast) @@literal_visitor.visit_this_0(self, ast) end def literal_Object(o) throw :not_literal end def literal_Factory(o) literal(o.model) end def literal_Program(o) literal(o.body) end def literal_LiteralString(o) o.value end def literal_QualifiedName(o) o.value end def literal_LiteralNumber(o) o.value end def literal_LiteralBoolean(o) o.value end def literal_LiteralUndef(o) nil end def literal_ConcatenatedString(o) # use double quoted string value if there is no interpolation throw :not_literal unless o.segments.size == 1 && o.segments[0].is_a?(Puppet::Pops::Model::LiteralString) o.segments[0].value end def literal_LiteralList(o) o.values.map { |v| literal(v) } end def literal_LiteralHash(o) o.entries.each_with_object({}) do |entry, result| key = literal(entry.key) throw :not_literal unless key.is_a?(String) result[key] = literal(entry.value) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/deferred_resolver.rb
lib/puppet/pops/evaluator/deferred_resolver.rb
# frozen_string_literal: true require_relative '../../../puppet/parser/script_compiler' module Puppet::Pops module Evaluator class DeferredValue def initialize(proc) @proc = proc end def resolve val = @proc.call # Deferred sensitive values will be marked as such in resolve_futures() if val.is_a?(Puppet::Pops::Types::PSensitiveType::Sensitive) val.unwrap else val end end end # Utility class to help resolve instances of Puppet::Pops::Types::PDeferredType::Deferred # class DeferredResolver DOLLAR = '$' DIG = 'dig' # Resolves and replaces all Deferred values in a catalog's resource attributes # found as direct values or nested inside Array, Hash or Sensitive values. # Deferred values inside of custom Object instances are not resolved as this # is expected to be done by such objects. # # @param facts [Puppet::Node::Facts] the facts object for the node # @param catalog [Puppet::Resource::Catalog] the catalog where all deferred values should be replaced # @param environment [Puppet::Node::Environment] the environment whose anonymous module methods # are to be mixed into the scope # @return [nil] does not return anything - the catalog is modified as a side effect # def self.resolve_and_replace(facts, catalog, environment = catalog.environment_instance, preprocess_deferred = true) compiler = Puppet::Parser::ScriptCompiler.new(environment, catalog.name, preprocess_deferred) resolver = new(compiler, preprocess_deferred) resolver.set_facts_variable(facts) # TODO: # # When scripting the trusted data are always local, but set them anyway # @scope.set_trusted(node.trusted_data) # # # Server facts are always about the local node's version etc. # @scope.set_server_facts(node.server_facts) resolver.resolve_futures(catalog) nil end # Resolves a value such that a direct Deferred, or any nested Deferred values # are resolved and used instead of the deferred value. # A direct Deferred value, or nested deferred values inside of Array, Hash or # Sensitive values are resolved and replaced inside of freshly created # containers. # # The resolution takes place in the topscope of the given compiler. # Variable values are supposed to already have been set. # # @param value [Object] the (possibly nested) value to resolve # @param compiler [Puppet::Parser::ScriptCompiler, Puppet::Parser::Compiler] the compiler in effect # @return [Object] the resolved value (a new Array, Hash, or Sensitive if needed), with all deferred values resolved # def self.resolve(value, compiler) resolver = new(compiler) resolver.resolve(value) end def initialize(compiler, preprocess_deferred = true) @compiler = compiler # Always resolve in top scope @scope = @compiler.topscope @deferred_class = Puppet::Pops::Types::TypeFactory.deferred.implementation_class @preprocess_deferred = preprocess_deferred end # @param facts [Puppet::Node::Facts] the facts to set in $facts in the compiler's topscope # def set_facts_variable(facts) @scope.set_facts(facts.nil? ? {} : facts.values) end def resolve_futures(catalog) catalog.resources.each do |r| overrides = {} r.parameters.each_pair do |k, v| resolved = resolve(v) case resolved when Puppet::Pops::Types::PSensitiveType::Sensitive # If the resolved value is instance of Sensitive - assign the unwrapped value # and mark it as sensitive if not already marked # resolved = resolved.unwrap mark_sensitive_parameters(r, k) when Puppet::Pops::Evaluator::DeferredValue # If the resolved value is a DeferredValue and it has an argument of type # PSensitiveType, mark it as sensitive. Since DeferredValues can nest, # we must walk all arguments, e.g. the DeferredValue may call the `epp` # function, where one of its arguments is a DeferredValue to call the # `vault:lookup` function. # # The DeferredValue.resolve method will unwrap the sensitive during # catalog application # if contains_sensitive_args?(v) mark_sensitive_parameters(r, k) end end overrides[k] = resolved end r.parameters.merge!(overrides) unless overrides.empty? end end # Return true if x contains an argument that is an instance of PSensitiveType: # # Deferred('new', [Sensitive, 'password']) # # Or an instance of PSensitiveType::Sensitive: # # Deferred('join', [['a', Sensitive('b')], ':']) # # Since deferred values can nest, descend into Arrays and Hash keys and values, # short-circuiting when the first occurrence is found. # def contains_sensitive_args?(x) case x when @deferred_class contains_sensitive_args?(x.arguments) when Array x.any? { |v| contains_sensitive_args?(v) } when Hash x.any? { |k, v| contains_sensitive_args?(k) || contains_sensitive_args?(v) } when Puppet::Pops::Types::PSensitiveType, Puppet::Pops::Types::PSensitiveType::Sensitive true else false end end private :contains_sensitive_args? def mark_sensitive_parameters(r, k) unless r.sensitive_parameters.include?(k.to_sym) r.sensitive_parameters = (r.sensitive_parameters + [k.to_sym]).freeze end end private :mark_sensitive_parameters def resolve(x) if x.instance_of?(@deferred_class) resolve_future(x) elsif x.is_a?(Array) x.map { |v| resolve(v) } elsif x.is_a?(Hash) result = {} x.each_pair { |k, v| result[k] = resolve(v) } result elsif x.is_a?(Puppet::Pops::Types::PSensitiveType::Sensitive) # rewrap in a new Sensitive after resolving any nested deferred values Puppet::Pops::Types::PSensitiveType::Sensitive.new(resolve(x.unwrap)) elsif x.is_a?(Puppet::Pops::Types::PBinaryType::Binary) # use the ASCII-8BIT string that it wraps x.binary_buffer else x end end def resolve_lazy_args(x) case x when DeferredValue x.resolve when Array x.map { |v| resolve_lazy_args(v) } when Hash result = {} x.each_pair { |k, v| result[k] = resolve_lazy_args(v) } result when Puppet::Pops::Types::PSensitiveType::Sensitive # rewrap in a new Sensitive after resolving any nested deferred values Puppet::Pops::Types::PSensitiveType::Sensitive.new(resolve_lazy_args(x.unwrap)) else x end end private :resolve_lazy_args def resolve_future(f) # If any of the arguments to a future is a future it needs to be resolved first func_name = f.name mapped_arguments = map_arguments(f.arguments) # if name starts with $ then this is a call to dig if func_name[0] == DOLLAR var_name = func_name[1..] func_name = DIG mapped_arguments.insert(0, @scope[var_name]) end if @preprocess_deferred # call the function (name in deferred, or 'dig' for a variable) @scope.call_function(func_name, mapped_arguments) else # call the function later DeferredValue.new( proc { # deferred functions can have nested deferred arguments resolved_arguments = mapped_arguments.map { |arg| resolve_lazy_args(arg) } @scope.call_function(func_name, resolved_arguments) } ) end end def map_arguments(args) return [] if args.nil? args.map { |v| resolve(v) } end private :map_arguments end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/closure.rb
lib/puppet/pops/evaluator/closure.rb
# frozen_string_literal: true module Puppet::Pops module Evaluator class Jumper < Exception # rubocop:disable Lint/InheritException attr_reader :value attr_reader :file attr_reader :line def initialize(value, file, line) @value = value @file = file @line = line end end class Next < Jumper; end class Return < Jumper; end class PuppetStopIteration < StopIteration attr_reader :file attr_reader :line attr_reader :pos def initialize(file, line, pos = nil) @file = file @line = line @pos = pos end def message "break() from context where this is illegal" end end # A Closure represents logic bound to a particular scope. # As long as the runtime (basically the scope implementation) has the behavior of Puppet 3x it is not # safe to return and later use this closure. # # The 3x scope is essentially a named scope with an additional internal local/ephemeral nested scope state. # In 3x there is no way to directly refer to the nested scopes, instead, the named scope must be in a particular # state. Specifically, closures that require a local/ephemeral scope to exist at a later point will fail. # It is safe to call a closure (even with 3x scope) from the very same place it was defined, but not # returning it and expecting the closure to reference the scope's state at the point it was created. # # Note that this class is a CallableSignature, and the methods defined there should be used # as the API for obtaining information in a callable-implementation agnostic way. # class Closure < CallableSignature attr_reader :evaluator attr_reader :model attr_reader :enclosing_scope def initialize(evaluator, model) @evaluator = evaluator @model = model end # Evaluates a closure in its enclosing scope after having matched given arguments with parameters (from left to right) # @api public def call(*args) call_with_scope(enclosing_scope, args) end # This method makes a Closure compatible with a Dispatch. This is used when the closure is wrapped in a Function # and the function is called. (Saves an extra Dispatch that just delegates to a Closure and avoids having two # checks of the argument type/arity validity). # @api private def invoke(instance, calling_scope, args, &block) enclosing_scope.with_global_scope do |global_scope| call_with_scope(global_scope, args, &block) end end def call_by_name_with_scope(scope, args_hash, enforce_parameters) call_by_name_internal(scope, args_hash, enforce_parameters) end def call_by_name(args_hash, enforce_parameters) call_by_name_internal(enclosing_scope, args_hash, enforce_parameters) end # Call closure with argument assignment by name def call_by_name_internal(closure_scope, args_hash, enforce_parameters) if enforce_parameters # Push a temporary parameter scope used while resolving the parameter defaults closure_scope.with_parameter_scope(closure_name, parameter_names) do |param_scope| # Assign all non-nil values, even those that represent non-existent parameters. args_hash.each { |k, v| param_scope[k] = v unless v.nil? } parameters.each do |p| name = p.name arg = args_hash[name] if arg.nil? # Arg either wasn't given, or it was undef if p.value.nil? # No default. Assign nil if the args_hash included it param_scope[name] = nil if args_hash.include?(name) else param_scope[name] = param_scope.evaluate(name, p.value, closure_scope, @evaluator) end end end args_hash = param_scope.to_hash end Types::TypeMismatchDescriber.validate_parameters(closure_name, params_struct, args_hash) result = catch(:next) do @evaluator.evaluate_block_with_bindings(closure_scope, args_hash, @model.body) end Types::TypeAsserter.assert_instance_of(nil, return_type, result) do "value returned from #{closure_name}" end else @evaluator.evaluate_block_with_bindings(closure_scope, args_hash, @model.body) end end private :call_by_name_internal def parameters @model.parameters end # Returns the number of parameters (required and optional) # @return [Integer] the total number of accepted parameters def parameter_count # yes, this is duplication of code, but it saves a method call @model.parameters.size end # @api public def parameter_names @model.parameters.collect(&:name) end def return_type @return_type ||= create_return_type end # @api public # rubocop:disable Naming/MemoizedInstanceVariableName def type @callable ||= create_callable_type end # rubocop:enable Naming/MemoizedInstanceVariableName # @api public def params_struct @params_struct ||= create_params_struct end # @api public def last_captures_rest? last = @model.parameters[-1] last && last.captures_rest end # @api public def block_name # TODO: Lambda's does not support blocks yet. This is a placeholder 'unsupported_block' end CLOSURE_NAME = 'lambda' # @api public def closure_name CLOSURE_NAME end class Dynamic < Closure def initialize(evaluator, model, scope) @enclosing_scope = scope super(evaluator, model) end def enclosing_scope @enclosing_scope end def call(*args) # A return from an unnamed closure is treated as a return from the context evaluating # calling this closure - that is, as if it was the return call itself. # jumper = catch(:return) do return call_with_scope(enclosing_scope, args) end raise jumper end end class Named < Closure def initialize(name, evaluator, model) @name = name super(evaluator, model) end def closure_name @name end # The assigned enclosing scope, or global scope if enclosing scope was initialized to nil # def enclosing_scope # Named closures are typically used for puppet functions and they cannot be defined # in an enclosing scope as they are cashed and reused. They need to bind to the # global scope at time of use rather at time of definition. # Unnamed closures are always a runtime construct, they are never bound by a loader # and are thus garbage collected at end of a compilation. # Puppet.lookup(:global_scope) { {} } end end private def call_with_scope(scope, args) variable_bindings = combine_values_with_parameters(scope, args) final_args = parameters.reduce([]) do |tmp_args, param| if param.captures_rest tmp_args.concat(variable_bindings[param.name]) else tmp_args << variable_bindings[param.name] end end if type.callable_with?(final_args, block_type) result = catch(:next) do @evaluator.evaluate_block_with_bindings(scope, variable_bindings, @model.body) end Types::TypeAsserter.assert_instance_of(nil, return_type, result) do "value returned from #{closure_name}" end else tc = Types::TypeCalculator.singleton args_type = tc.infer_set(final_args) raise ArgumentError, Types::TypeMismatchDescriber.describe_signatures(closure_name, [self], args_type) end end def combine_values_with_parameters(scope, args) scope.with_parameter_scope(closure_name, parameter_names) do |param_scope| parameters.each_with_index do |parameter, index| param_captures = parameter.captures_rest default_expression = parameter.value if index >= args.size if default_expression # not given, has default value = param_scope.evaluate(parameter.name, default_expression, scope, @evaluator) if param_captures && !value.is_a?(Array) # correct non array default value value = [value] end elsif param_captures # not given, does not have default value = [] # default for captures rest is an empty array else @evaluator.fail(Issues::MISSING_REQUIRED_PARAMETER, parameter, { :param_name => parameter.name }) end else given_argument = args[index] if param_captures # get excess arguments value = args[(parameter_count - 1)..] # If the input was a single nil, or undef, and there is a default, use the default # This supports :undef in case it was used in a 3x data structure and it is passed as an arg # if value.size == 1 && (given_argument.nil? || given_argument == :undef) && default_expression value = param_scope.evaluate(parameter.name, default_expression, scope, @evaluator) # and ensure it is an array value = [value] unless value.is_a?(Array) end else value = given_argument end end param_scope[parameter.name] = value end param_scope.to_hash end end def create_callable_type types = [] from = 0 to = 0 in_optional_parameters = false closure_scope = enclosing_scope parameters.each do |param| type, param_range = create_param_type(param, closure_scope) types << type if param_range[0] == 0 in_optional_parameters = true elsif param_range[0] != 0 && in_optional_parameters @evaluator.fail(Issues::REQUIRED_PARAMETER_AFTER_OPTIONAL, param, { :param_name => param.name }) end from += param_range[0] to += param_range[1] end param_types = Types::PTupleType.new(types, Types::PIntegerType.new(from, to)) # The block_type for a Closure is always nil for now, see comment in block_name above Types::PCallableType.new(param_types, nil, return_type) end def create_params_struct type_factory = Types::TypeFactory members = {} closure_scope = enclosing_scope parameters.each do |param| arg_type, _ = create_param_type(param, closure_scope) key_type = type_factory.string(param.name.to_s) key_type = type_factory.optional(key_type) unless param.value.nil? members[key_type] = arg_type end type_factory.struct(members) end def create_return_type if @model.return_type @evaluator.evaluate(@model.return_type, @enclosing_scope) else Types::PAnyType::DEFAULT end end def create_param_type(param, closure_scope) type = if param.type_expr @evaluator.evaluate(param.type_expr, closure_scope) else Types::PAnyType::DEFAULT end if param.captures_rest && type.is_a?(Types::PArrayType) # An array on a slurp parameter is how a size range is defined for a # slurp (Array[Integer, 1, 3] *$param). However, the callable that is # created can't have the array in that position or else type checking # will require the parameters to be arrays, which isn't what is # intended. The array type contains the intended information and needs # to be unpacked. param_range = type.size_range type = type.element_type elsif param.captures_rest && !type.is_a?(Types::PArrayType) param_range = ANY_NUMBER_RANGE elsif param.value param_range = OPTIONAL_SINGLE_RANGE else param_range = REQUIRED_SINGLE_RANGE end [type, param_range] end # Produces information about parameters compatible with a 4x Function (which can have multiple signatures) def signatures [self] end ANY_NUMBER_RANGE = [0, Float::INFINITY] OPTIONAL_SINGLE_RANGE = [0, 1] REQUIRED_SINGLE_RANGE = [1, 1] end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/compare_operator.rb
lib/puppet/pops/evaluator/compare_operator.rb
# frozen_string_literal: true module Puppet::Pops module Evaluator # Compares the puppet DSL way # # ==Equality # All string vs. numeric equalities check for numeric equality first, then string equality # Arrays are equal to arrays if they have the same length, and each element #equals # Hashes are equal to hashes if they have the same size and keys and values #equals. # All other objects are equal if they are ruby #== equal # class CompareOperator include Utils # Provides access to the Puppet 3.x runtime (scope, etc.) # This separation has been made to make it easier to later migrate the evaluator to an improved runtime. # include Runtime3Support def initialize @@equals_visitor ||= Visitor.new(self, "equals", 1, 1) @@compare_visitor ||= Visitor.new(self, "cmp", 1, 1) @@match_visitor ||= Visitor.new(self, "match", 2, 2) @@include_visitor ||= Visitor.new(self, "include", 2, 2) end def equals(a, b) @@equals_visitor.visit_this_1(self, a, b) end # Performs a comparison of a and b, and return > 0 if a is bigger, 0 if equal, and < 0 if b is bigger. # Comparison of String vs. Numeric always compares using numeric. def compare(a, b) @@compare_visitor.visit_this_1(self, a, b) end # Performs a match of a and b, and returns true if b matches a def match(a, b, scope = nil) @@match_visitor.visit_this_2(self, b, a, scope) end # Answers is b included in a def include?(a, b, scope) @@include_visitor.visit_this_2(self, a, b, scope) end protected def cmp_String(a, b) return a.casecmp(b) if b.is_a?(String) raise ArgumentError, _("A String is not comparable to a non String") end # Equality is case independent. def equals_String(a, b) return false unless b.is_a?(String) a.casecmp(b) == 0 end def cmp_Numeric(a, b) case b when Numeric a <=> b when Time::Timespan, Time::Timestamp -(b <=> a) # compare other way and invert result else raise ArgumentError, _("A Numeric is not comparable to non Numeric") end end def equals_Numeric(a, b) if b.is_a?(Numeric) a == b else false end end def equals_Array(a, b) return false unless b.is_a?(Array) && a.size == b.size a.each_index { |i| return false unless equals(a.slice(i), b.slice(i)) } true end def equals_Hash(a, b) return false unless b.is_a?(Hash) && a.size == b.size a.each { |ak, av| return false unless equals(b[ak], av) } true end def cmp_Symbol(a, b) if b.is_a?(Symbol) a <=> b else raise ArgumentError, _("Symbol not comparable to non Symbol") end end def cmp_Timespan(a, b) raise ArgumentError, _('Timespans are only comparable to Timespans, Integers, and Floats') unless b.is_a?(Time::Timespan) || b.is_a?(Integer) || b.is_a?(Float) a <=> b end def cmp_Timestamp(a, b) raise ArgumentError, _('Timestamps are only comparable to Timestamps, Integers, and Floats') unless b.is_a?(Time::Timestamp) || b.is_a?(Integer) || b.is_a?(Float) a <=> b end def cmp_Version(a, b) raise ArgumentError, _('Versions not comparable to non Versions') unless b.is_a?(SemanticPuppet::Version) a <=> b end def cmp_Object(a, b) raise ArgumentError, _('Only Strings, Numbers, Timespans, Timestamps, and Versions are comparable') end def equals_Object(a, b) a == b end def equals_NilClass(a, b) # :undef supported in case it is passed from a 3x data structure b.nil? || b == :undef end def equals_Symbol(a, b) # :undef supported in case it is passed from a 3x data structure a == b || a == :undef && b.nil? end def include_Object(a, b, scope) false end def include_String(a, b, scope) case b when String # substring search downcased a.downcase.include?(b.downcase) when Regexp matched = a.match(b) # nil, or MatchData set_match_data(matched, scope) # creates ephemeral !!matched # match (convert to boolean) when Numeric # convert string to number, true if == equals(a, b) else false end end def include_Binary(a, b, scope) case b when Puppet::Pops::Types::PBinaryType::Binary a.binary_buffer.include?(b.binary_buffer) when String a.binary_buffer.include?(b) when Numeric a.binary_buffer.bytes.include?(b) else false end end def include_Array(a, b, scope) case b when Regexp matched = nil a.each do |element| next unless element.is_a? String matched = element.match(b) # nil, or MatchData break if matched end # Always set match data, a "not found" should not keep old match data visible set_match_data(matched, scope) # creates ephemeral !!matched when String, SemanticPuppet::Version a.any? { |element| match(b, element, scope) } when Types::PAnyType a.each { |element| return true if b.instance?(element) } false else a.each { |element| return true if equals(element, b) } false end end def include_Hash(a, b, scope) include?(a.keys, b, scope) end def include_VersionRange(a, b, scope) Types::PSemVerRangeType.include?(a, b) end # Matches in general by using == operator def match_Object(pattern, a, scope) equals(a, pattern) end # Matches only against strings def match_Regexp(regexp, left, scope) return false unless left.is_a? String matched = regexp.match(left) set_match_data(matched, scope) unless scope.nil? # creates or clears ephemeral !!matched # convert to boolean end # Matches against semvers and strings def match_Version(version, left, scope) case left when SemanticPuppet::Version version == left when String begin version == SemanticPuppet::Version.parse(left) rescue ArgumentError false end else false end end # Matches against semvers and strings def match_VersionRange(range, left, scope) Types::PSemVerRangeType.include?(range, left) end def match_PAnyType(any_type, left, scope) # right is a type and left is not - check if left is an instance of the given type # (The reverse is not terribly meaningful - computing which of the case options that first produces # an instance of a given type). # any_type.instance?(left) end def match_Array(array, left, scope) return false unless left.is_a?(Array) return false unless left.length == array.length array.each_with_index.all? { |pattern, index| match(left[index], pattern, scope) } end def match_Hash(hash, left, scope) return false unless left.is_a?(Hash) hash.all? { |x, y| match(left[x], y, scope) } end def match_Symbol(symbol, left, scope) return true if symbol == :default equals(left, default) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/runtime3_resource_support.rb
lib/puppet/pops/evaluator/runtime3_resource_support.rb
# frozen_string_literal: true module Puppet::Pops module Evaluator # @api private module Runtime3ResourceSupport CLASS_STRING = 'class' def self.create_resources(file, line, scope, virtual, exported, type_name, resource_titles, evaluated_parameters) env = scope.environment # loader = Adapters::LoaderAdapter.loader_for_model_object(o, scope) if type_name.is_a?(String) && type_name.casecmp(CLASS_STRING) == 0 # Resolve a 'class' and its titles resource_titles = resource_titles.collect do |a_title| hostclass = env.known_resource_types.find_hostclass(a_title) hostclass ? hostclass.name : a_title end # resolved type is just the string CLASS resolved_type = CLASS_STRING else # resolve a resource type - pcore based, ruby impl or user defined resolved_type = find_resource_type(scope, type_name) end # TODO: Unknown resource causes creation of Resource to fail with ArgumentError, should give # a proper Issue. Now the result is "Error while evaluating a Resource Statement" with the message # from the raised exception. (It may be good enough). unless resolved_type # TODO: do this the right way raise ArgumentError, _("Unknown resource type: '%{type}'") % { type: type_name } end # Build a resource for each title - use the resolved *type* as opposed to a reference # as this makes the created resource retain the type instance. # resource_titles.map do |resource_title| resource = Puppet::Parser::Resource.new( resolved_type, resource_title, :parameters => evaluated_parameters, :file => file, :line => line, :kind => Puppet::Resource.to_kind(resolved_type), :exported => exported, :virtual => virtual, # WTF is this? Which source is this? The file? The name of the context ? :source => scope.source, :scope => scope, :strict => true ) # If this resource type supports inheritance (e.g. 'class') the parent chain must be walked # This impl delegates to the resource type to figure out what is needed. # if resource.resource_type.is_a? Puppet::Resource::Type resource.resource_type.instantiate_resource(scope, resource) end scope.compiler.add_resource(scope, resource) # Classes are evaluated immediately scope.compiler.evaluate_classes([resource_title], scope, false) if resolved_type == CLASS_STRING # Turn the resource into a PTypeType (a reference to a resource type) # weed out nil's resource_to_ptype(resource) end end def self.find_resource_type(scope, type_name) find_builtin_resource_type(scope, type_name) || find_defined_resource_type(scope, type_name) end def self.find_resource_type_or_class(scope, name) find_builtin_resource_type(scope, name) || find_defined_resource_type(scope, name) || find_hostclass(scope, name) end def self.resource_to_ptype(resource) return nil if resource.nil? # inference returns the meta type since the 3x Resource is an alternate way to describe a type Puppet::Pops::Types::TypeCalculator.singleton().infer(resource).type end def self.find_main_class(scope) # Find the main class (known as ''), it does not have to be in the catalog scope.environment.known_resource_types.find_hostclass('') end def self.find_hostclass(scope, class_name) scope.environment.known_resource_types.find_hostclass(class_name) end def self.find_builtin_resource_type(scope, type_name) if type_name.include?(':') # Skip the search for built in types as they are always in global namespace # (At least for now). return nil end loader = scope.compiler.loaders.private_environment_loader loaded = loader.load(:resource_type_pp, type_name) if loaded return loaded end # horrible - should be loaded by a "last loader" in 4.x loaders instead. Puppet::Type.type(type_name) end private_class_method :find_builtin_resource_type def self.find_defined_resource_type(scope, type_name) krt = scope.environment.known_resource_types krt.find_definition(type_name) end private_class_method :find_defined_resource_type end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/relationship_operator.rb
lib/puppet/pops/evaluator/relationship_operator.rb
# frozen_string_literal: true module Puppet::Pops module Evaluator # The RelationshipOperator implements the semantics of the -> <- ~> <~ operators creating relationships or notification # relationships between the left and right hand side's references to resources. # # This is separate class since a second level of evaluation is required that transforms string in left or right hand # to type references. The task of "making a relationship" is delegated to the "runtime support" class that is included. # This is done to separate the concerns of the new evaluator from the 3x runtime; messy logic goes into the runtime support # module. Later when more is cleaned up this can be simplified further. # class RelationshipOperator # Provides access to the Puppet 3.x runtime (scope, etc.) # This separation has been made to make it easier to later migrate the evaluator to an improved runtime. # include Runtime3Support class IllegalRelationshipOperandError < RuntimeError attr_reader :operand def initialize operand @operand = operand end end class NotCatalogTypeError < RuntimeError attr_reader :type def initialize type @type = type end end def initialize @type_transformer_visitor = Visitor.new(self, "transform", 1, 1) @type_calculator = Types::TypeCalculator.new() tf = Types::TypeFactory @catalog_type = tf.variant(tf.catalog_entry, tf.type_type(tf.catalog_entry)) end def transform(o, scope) @type_transformer_visitor.visit_this_1(self, o, scope) end # Catch all non transformable objects # @api private def transform_Object(o, scope) raise IllegalRelationshipOperandError, o end # A Resource is by definition a Catalog type, but of 3.x type # @api private def transform_Resource(o, scope) Types::TypeFactory.resource(o.type, o.title) end # A string must be a type reference in string format # @api private def transform_String(o, scope) assert_catalog_type(Types::TypeParser.singleton.parse(o), scope) end # A qualified name is short hand for a class with this name # @api private def transform_QualifiedName(o, scope) Types::TypeFactory.host_class(o.value) end # Types are what they are, just check the type # @api private def transform_PAnyType(o, scope) assert_catalog_type(o, scope) end # This transforms a 3x Collector (the result of evaluating a 3x AST::Collection). # It is passed through verbatim since it is evaluated late by the compiler. At the point # where the relationship is evaluated, it is simply recorded with the compiler for later evaluation. # If one of the sides of the relationship is a Collector it is evaluated before the actual # relationship is formed. (All of this happens at a later point in time. # def transform_Collector(o, scope) o end def transform_AbstractCollector(o, scope) o end # Array content needs to be transformed def transform_Array(o, scope) o.map { |x| transform(x, scope) } end # Asserts (and returns) the type if it is a PCatalogEntryType # (A PCatalogEntryType is the base class of PClassType, and PResourceType). # def assert_catalog_type(o, scope) unless @type_calculator.assignable?(@catalog_type, o) raise NotCatalogTypeError, o end # TODO must check if this is an abstract PResourceType (i.e. without a type_name) - which should fail ? # e.g. File -> File (and other similar constructs) - maybe the catalog protects against this since references # may be to future objects... o end RELATIONSHIP_OPERATORS = ['->', '~>', '<-', '<~'].freeze REVERSE_OPERATORS = ['<-', '<~'].freeze RELATION_TYPE = { '->' => :relationship, '<-' => :relationship, '~>' => :subscription, '<~' => :subscription }.freeze # Evaluate a relationship. # TODO: The error reporting is not fine grained since evaluation has already taken place # There is no references to the original source expressions at this point, only the overall # relationship expression. (e.g.. the expression may be ['string', func_call(), etc.] -> func_call()) # To implement this, the general evaluator needs to be able to track each evaluation result and associate # it with a corresponding expression. This structure should then be passed to the relationship operator. # def evaluate(left_right_evaluated, relationship_expression, scope) # assert operator (should have been validated, but this logic makes assumptions which would # screw things up royally). Better safe than sorry. unless RELATIONSHIP_OPERATORS.include?(relationship_expression.operator) fail(Issues::UNSUPPORTED_OPERATOR, relationship_expression, { :operator => relationship_expression.operator }) end begin # Turn each side into an array of types (this also asserts their type) # (note wrap in array first if value is not already an array) # # TODO: Later when objects are Puppet Runtime Objects and know their type, it will be more efficient to check/infer # the type first since a chained operation then does not have to visit each element again. This is not meaningful now # since inference needs to visit each object each time, and this is what the transformation does anyway). # # real is [left, right], and both the left and right may be a single value or an array. In each case all content # should be flattened, and then transformed to a type. left or right may also be a value that is transformed # into an array, and thus the resulting left and right must be flattened individually # Once flattened, the operands should be sets (to remove duplicate entries) # real = left_right_evaluated.collect { |x| [x].flatten.collect { |y| transform(y, scope) } } real[0].flatten! real[1].flatten! real[0].uniq! real[1].uniq! # reverse order if operator is Right to Left source, target = reverse_operator?(relationship_expression) ? real.reverse : real # Add the relationships to the catalog source.each { |s| target.each { |t| add_relationship(s, t, RELATION_TYPE[relationship_expression.operator], scope) } } # The result is the transformed source RHS unless it is empty, in which case the transformed LHS is returned. # This closes the gap created by an empty set of references in a chain of relationship # such that X -> [ ] -> Y results in X -> Y. # result = real[1].empty? ? real[0] : real[1] if real[1].empty? # right side empty, simply use the left (whatever it may be) result = real[0] else right = real[1] if right.size == 1 && right[0].is_a?(Puppet::Pops::Evaluator::Collectors::AbstractCollector) # the collector when evaluated later may result in an empty set, if so, the # lazy relationship forming logic needs to have access to the left value. adapter = Puppet::Pops::Adapters::EmptyAlternativeAdapter.adapt(right[0]) adapter.empty_alternative = real[0] end result = right end result rescue NotCatalogTypeError => e fail(Issues::NOT_CATALOG_TYPE, relationship_expression, { :type => @type_calculator.string(e.type) }) rescue IllegalRelationshipOperandError => e fail(Issues::ILLEGAL_RELATIONSHIP_OPERAND_TYPE, relationship_expression, { :operand => e.operand }) end end def reverse_operator?(o) REVERSE_OPERATORS.include?(o.operator) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/callable_signature.rb
lib/puppet/pops/evaluator/callable_signature.rb
# frozen_string_literal: true # CallableSignature # === # A CallableSignature describes how something callable expects to be called. # Different implementation of this class are used for different types of callables. # # @api public # class Puppet::Pops::Evaluator::CallableSignature # Returns the names of the parameters as an array of strings. This does not include the name # of an optional block parameter. # # All implementations are not required to supply names for parameters. They may be used if present, # to provide user feedback in errors etc. but they are not authoritative about the number of # required arguments, optional arguments, etc. # # A derived class must implement this method. # # @return [Array<String>] - an array of names (that may be empty if names are unavailable) # # @api public # def parameter_names raise NotImplementedError end # Returns a PCallableType with the type information, required and optional count, and type information about # an optional block. # # A derived class must implement this method. # # @return [Puppet::Pops::Types::PCallableType] # @api public # def type raise NotImplementedError end # Returns the expected type for an optional block. The type may be nil, which means that the callable does # not accept a block. If a type is returned it is one of Callable, Optional[Callable], Variant[Callable,...], # or Optional[Variant[Callable, ...]]. The Variant type is used when multiple signatures are acceptable. # The Optional type is used when the block is optional. # # @return [Puppet::Pops::Types::PAnyType, nil] the expected type of a block given as the last parameter in a call. # # @api public # def block_type type.block_type end # Returns the name of the block parameter if the callable accepts a block. # @return [String] the name of the block parameter # A derived class must implement this method. # @api public # def block_name raise NotImplementedError end # Returns a range indicating the optionality of a block. One of [0,0] (does not accept block), [0,1] (optional # block), and [1,1] (block required) # # @return [Array(Integer, Integer)] the range of the block parameter # def block_range type.block_range end # Returns the range of required/optional argument values as an array of [min, max], where an infinite # end is given as Float::INFINITY. To test against infinity, use the infinity? method. # # @return [Array[Integer, Numeric]] - an Array with [min, max] # # @api public # def args_range type.size_range end # Returns true if the last parameter captures the rest of the arguments, with a possible cap, as indicated # by the `args_range` method. # A derived class must implement this method. # # @return [Boolean] true if last parameter captures the rest of the given arguments (up to a possible cap) # @api public # def last_captures_rest? raise NotImplementedError end # Returns true if the given x is infinity # @return [Boolean] true, if given value represents infinity # # @api public # def infinity?(x) x == Float::INFINITY end # @return [Boolean] true if this signature represents an argument mismatch, false otherwise # # @api private def argument_mismatch_handler? false end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/collectors/catalog_collector.rb
lib/puppet/pops/evaluator/collectors/catalog_collector.rb
# frozen_string_literal: true class Puppet::Pops::Evaluator::Collectors::CatalogCollector < Puppet::Pops::Evaluator::Collectors::AbstractCollector # Creates a CatalogCollector using the AbstractCollector's # constructor to set the scope and overrides # # param [Puppet::CompilableResourceType] type the resource type to be collected # param [Proc] query the query which defines which resources to match def initialize(scope, type, query, overrides = nil) super(scope, overrides) @query = query @type = Puppet::Resource.new(type, 'whatever').type end # Collects virtual resources based off a collection in a manifest def collect t = @type q = @query scope.compiler.resources.find_all do |resource| resource.type == t && (q ? q.call(resource) : true) end end def to_s "Catalog-Collector[#{@type}]" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/collectors/exported_collector.rb
lib/puppet/pops/evaluator/collectors/exported_collector.rb
# frozen_string_literal: true class Puppet::Pops::Evaluator::Collectors::ExportedCollector < Puppet::Pops::Evaluator::Collectors::AbstractCollector # Creates an ExportedCollector using the AbstractCollector's # constructor to set the scope and overrides # # param [Puppet::CompilableResourceType] type the resource type to be collected # param [Array] equery an array representation of the query (exported query) # param [Proc] cquery a proc representation of the query (catalog query) def initialize(scope, type, equery, cquery, overrides = nil) super(scope, overrides) @equery = equery @cquery = cquery @type = Puppet::Resource.new(type, 'whatever').type end # Ensures that storeconfigs is present before calling AbstractCollector's # evaluate method def evaluate if Puppet[:storeconfigs] != true return false end super end # Collect exported resources as defined by an exported # collection. Used with PuppetDB def collect resources = [] time = Puppet::Util.thinmark do t = @type q = @cquery resources = scope.compiler.resources.find_all do |resource| resource.type == t && resource.exported? && (q.nil? || q.call(resource)) end found = Puppet::Resource.indirection .search(@type, :host => @scope.compiler.node.name, :filter => @equery, :scope => @scope) found_resources = found.map { |x| x.is_a?(Puppet::Parser::Resource) ? x : x.to_resource(@scope) } found_resources.each do |item| existing = @scope.findresource(item.resource_type, item.title) if existing unless existing.collector_id == item.collector_id raise Puppet::ParseError, _("A duplicate resource was found while collecting exported resources, with the type and title %{title}") % { title: item.ref } end else item.exported = false @scope.compiler.add_resource(@scope, item) resources << item end end end scope.debug("Collected %s %s resource%s in %.2f seconds" % [resources.length, @type, resources.length == 1 ? "" : "s", time]) resources end def to_s "Exported-Collector[#{@type}]" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/collectors/abstract_collector.rb
lib/puppet/pops/evaluator/collectors/abstract_collector.rb
# frozen_string_literal: true class Puppet::Pops::Evaluator::Collectors::AbstractCollector attr_reader :scope # The collector's hash of overrides {:parameters => params} attr_reader :overrides # The set of collected resources attr_reader :collected # An empty array which will be returned by the unresolved_resources # method unless we have a FixSetCollector EMPTY_RESOURCES = [].freeze # Initialized the instance variables needed by the base # collector class to perform evaluation # # @param [Puppet::Parser::Scope] scope # # @param [Hash] overrides a hash of optional overrides # @options opts [Array] :parameters # @options opts [String] :file # @options opts [Array] :line # @options opts [Puppet::Resource::Type] :source # @options opts [Puppet::Parser::Scope] :scope def initialize(scope, overrides = nil) @collected = {} @scope = scope unless overrides.nil? || overrides[:parameters] raise ArgumentError, _("Exported resource try to override without parameters") end @overrides = overrides end # Collects resources and marks collected objects as non-virtual. Also # handles overrides. # # @return [Array] the resources we have collected def evaluate objects = collect.each do |obj| obj.virtual = false end return false if objects.empty? if @overrides and !objects.empty? overrides[:source].override = true objects.each do |res| next if @collected.include?(res.ref) t = res.type t = Puppet::Pops::Evaluator::Runtime3ResourceSupport.find_resource_type(scope, t) newres = Puppet::Parser::Resource.new(t, res.title, @overrides) scope.compiler.add_override(newres) end end objects.reject! { |o| @collected.include?(o.ref) } return false if objects.empty? objects.each_with_object(@collected) { |o, c| c[o.ref] = o; } objects end # This should only return an empty array unless we have # an FixedSetCollector, in which case it will return the # resources that have not yet been realized # # @return [Array] the resources that have not been resolved def unresolved_resources EMPTY_RESOURCES end # Collect the specified resources. The way this is done depends on which type # of collector we are dealing with. This method is implemented differently in # each of the three child classes # # @return [Array] the collected resources def collect raise NotImplementedError, "This method must be implemented by the child class" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/evaluator/collectors/fixed_set_collector.rb
lib/puppet/pops/evaluator/collectors/fixed_set_collector.rb
# frozen_string_literal: true class Puppet::Pops::Evaluator::Collectors::FixedSetCollector < Puppet::Pops::Evaluator::Collectors::AbstractCollector # Creates a FixedSetCollector using the AbstractCollector constructor # to set the scope. It is not possible for a collection to have # overrides in this case, since we have a fixed set of resources that # can be different types. # # @param [Array] resources the fixed set of resources we want to realize def initialize(scope, resources) super(scope) @resources = resources.is_a?(Array) ? resources.dup : [resources] end # Collects a fixed set of resources and realizes them. Used # by the realize function def collect resolved = [] result = @resources.each_with_object([]) do |ref, memo| res = @scope.findresource(ref.to_s) next unless res res.virtual = false memo << res resolved << ref end @resources -= resolved @scope.compiler.delete_collection(self) if @resources.empty? result end def unresolved_resources @resources end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false