repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/facts/memory.rb | lib/puppet/indirector/facts/memory.rb | # frozen_string_literal: true
require_relative '../../../puppet/node/facts'
require_relative '../../../puppet/indirector/memory'
class Puppet::Node::Facts::Memory < Puppet::Indirector::Memory
desc "Keep track of facts in memory but nowhere else. This is used for
one-time compiles, such as what the stand-alone `puppet` does.
To use this terminus, you must load it with the data you want it
to contain."
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/facts/rest.rb | lib/puppet/indirector/facts/rest.rb | # frozen_string_literal: true
require_relative '../../../puppet/node/facts'
require_relative '../../../puppet/indirector/rest'
class Puppet::Node::Facts::Rest < Puppet::Indirector::REST
desc "Find and save facts about nodes over HTTP via REST."
def find(request)
session = Puppet.lookup(:http_session)
api = session.route_to(:puppet)
_, facts = api.get_facts(
request.key,
environment: request.environment.to_s
)
facts
rescue Puppet::HTTP::ResponseError => e
if e.response.code == 404
return nil unless request.options[:fail_on_404]
_, body = parse_response(e.response)
msg = _("Find %{uri} resulted in 404 with the message: %{body}") % { uri: elide(e.response.url.path, 100), body: body }
raise Puppet::Error, msg
else
raise convert_to_http_error(e.response)
end
end
def save(request)
raise ArgumentError, _("PUT does not accept options") unless request.options.empty?
session = Puppet.lookup(:http_session)
api = session.route_to(:puppet)
api.put_facts(
request.key,
facts: request.instance,
environment: request.environment.to_s
)
# preserve existing behavior
nil
rescue Puppet::HTTP::ResponseError => e
# always raise even if fail_on_404 is false
raise convert_to_http_error(e.response)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/facts/yaml.rb | lib/puppet/indirector/facts/yaml.rb | # frozen_string_literal: true
require_relative '../../../puppet/node/facts'
require_relative '../../../puppet/indirector/yaml'
require_relative '../../../puppet/indirector/fact_search'
class Puppet::Node::Facts::Yaml < Puppet::Indirector::Yaml
desc "Store client facts as flat files, serialized using YAML, or
return deserialized facts from disk."
include Puppet::Indirector::FactSearch
def search(request)
node_names = []
Dir.glob(yaml_dir_path).each do |file|
facts = load_file(file)
if facts && node_matches?(facts, request.options)
node_names << facts.name
end
end
node_names
end
private
# Return the path to a given node's file.
def yaml_dir_path
base = Puppet.run_mode.server? ? Puppet[:yamldir] : Puppet[:clientyamldir]
File.join(base, 'facts', '*.yaml')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/facts/json.rb | lib/puppet/indirector/facts/json.rb | # frozen_string_literal: true
require_relative '../../../puppet/node/facts'
require_relative '../../../puppet/indirector/json'
require_relative '../../../puppet/indirector/fact_search'
class Puppet::Node::Facts::Json < Puppet::Indirector::JSON
desc "Store client facts as flat files, serialized using JSON, or
return deserialized facts from disk."
include Puppet::Indirector::FactSearch
def search(request)
node_names = []
Dir.glob(json_dir_path).each do |file|
facts = load_json_from_file(file, '')
if facts && node_matches?(facts, request.options)
node_names << facts.name
end
end
node_names
end
private
def json_dir_path
path("*")
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/facts/network_device.rb | lib/puppet/indirector/facts/network_device.rb | # frozen_string_literal: true
require_relative '../../../puppet/node/facts'
require_relative '../../../puppet/indirector/code'
class Puppet::Node::Facts::NetworkDevice < Puppet::Indirector::Code
desc "Retrieve facts from a network device."
def allow_remote_requests?
false
end
# Look a device's facts up through the current device.
def find(request)
result = Puppet::Node::Facts.new(request.key, Puppet::Util::NetworkDevice.current.facts)
result.add_local_facts
result.sanitize
result
end
def destroy(facts)
raise Puppet::DevError, _("You cannot destroy facts in the code store; it is only used for getting facts from a remote device")
end
def save(facts)
raise Puppet::DevError, _("You cannot save facts to the code store; it is only used for getting facts from a remote device")
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/facts/facter.rb | lib/puppet/indirector/facts/facter.rb | # frozen_string_literal: true
require_relative '../../../puppet/node/facts'
require_relative '../../../puppet/indirector/code'
class Puppet::Node::Facts::Facter < Puppet::Indirector::Code
desc "Retrieve facts from Facter. This provides a somewhat abstract interface
between Puppet and Facter. It's only `somewhat` abstract because it always
returns the local host's facts, regardless of what you attempt to find."
def allow_remote_requests?
false
end
def destroy(facts)
raise Puppet::DevError, _('You cannot destroy facts in the code store; it is only used for getting facts from Facter')
end
def save(facts)
raise Puppet::DevError, _('You cannot save facts to the code store; it is only used for getting facts from Facter')
end
# Lookup a host's facts up in Facter.
def find(request)
Puppet.runtime[:facter].reset
# Note: we need to setup puppet's external search paths before adding the puppetversion
# fact. This is because in Facter 2.x, the first `Puppet.runtime[:facter].add` causes Facter to create
# its directory loaders which cannot be changed, meaning other external facts won't
# be resolved. (PUP-4607)
self.class.setup_external_search_paths(request)
self.class.setup_search_paths(request)
# Initialize core Puppet facts, such as puppetversion
Puppet.initialize_facts
result = if request.options[:resolve_options]
raise(Puppet::Error, _("puppet facts show requires version 4.0.40 or greater of Facter.")) unless Facter.respond_to?(:resolve)
find_with_options(request)
elsif Puppet[:include_legacy_facts]
# to_hash returns both structured and legacy facts
Puppet::Node::Facts.new(request.key, Puppet.runtime[:facter].to_hash)
else
# resolve does not return legacy facts unless requested
facts = Puppet.runtime[:facter].resolve('')
# some versions of Facter 4 return a Facter::FactCollection instead of
# a Hash, breaking API compatibility, so force a hash using `to_h`
Puppet::Node::Facts.new(request.key, facts.to_h)
end
result.add_local_facts(request.options[:user_query])
result.sanitize
result
end
def self.setup_search_paths(request)
# Add any per-module fact directories to facter's search path
dirs = request.environment.modulepath.collect do |dir|
%w[lib plugins].map do |subdirectory|
Dir.glob("#{dir}/*/#{subdirectory}/facter")
end
end.flatten + Puppet[:factpath].split(File::PATH_SEPARATOR)
dirs = dirs.select do |dir|
next false unless FileTest.directory?(dir)
# Even through we no longer directly load facts in the terminus,
# print out each .rb in the facts directory as module
# developers may find that information useful for debugging purposes
if Puppet::Util::Log.sendlevel?(:info)
Puppet.info _("Loading facts")
Dir.glob("#{dir}/*.rb").each do |file|
Puppet.debug { "Loading facts from #{file}" }
end
end
true
end
dirs << request.options[:custom_dir] if request.options[:custom_dir]
Puppet.runtime[:facter].search(*dirs)
end
def self.setup_external_search_paths(request)
# Add any per-module external fact directories to facter's external search path
dirs = []
request.environment.modules.each do |m|
next unless m.has_external_facts?
dir = m.plugin_fact_directory
Puppet.debug { "Loading external facts from #{dir}" }
dirs << dir
end
# Add system external fact directory if it exists
if FileTest.directory?(Puppet[:pluginfactdest])
dir = Puppet[:pluginfactdest]
Puppet.debug { "Loading external facts from #{dir}" }
dirs << dir
end
dirs << request.options[:external_dir] if request.options[:external_dir]
Puppet.runtime[:facter].search_external dirs
end
private
def find_with_options(request)
options = request.options
options_for_facter = ''.dup
options_for_facter += options[:user_query].join(' ')
options_for_facter += " --config #{options[:config_file]}" if options[:config_file]
options_for_facter += " --show-legacy" if options[:show_legacy]
options_for_facter += " --no-block" if options[:no_block] == false
options_for_facter += " --no-cache" if options[:no_cache] == false
options_for_facter += " --timing" if options[:timing]
Puppet::Node::Facts.new(request.key, Puppet.runtime[:facter].resolve(options_for_facter))
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/file_bucket_file/selector.rb | lib/puppet/indirector/file_bucket_file/selector.rb | # frozen_string_literal: true
require_relative '../../../puppet/indirector/code'
module Puppet::FileBucketFile
class Selector < Puppet::Indirector::Code
desc "Select the terminus based on the request"
def select(request)
if request.protocol == 'https'
:rest
else
:file
end
end
def get_terminus(request)
indirection.terminus(select(request))
end
def head(request)
get_terminus(request).head(request)
end
def find(request)
get_terminus(request).find(request)
end
def save(request)
get_terminus(request).save(request)
end
def search(request)
get_terminus(request).search(request)
end
def destroy(request)
get_terminus(request).destroy(request)
end
def authorized?(request)
terminus = get_terminus(request)
if terminus.respond_to?(:authorized?)
terminus.authorized?(request)
else
true
end
end
def validate_key(request)
get_terminus(request).validate(request)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/file_bucket_file/rest.rb | lib/puppet/indirector/file_bucket_file/rest.rb | # frozen_string_literal: true
require_relative '../../../puppet/indirector/rest'
require_relative '../../../puppet/file_bucket/file'
module Puppet::FileBucketFile
class Rest < Puppet::Indirector::REST
desc "This is a REST based mechanism to send/retrieve file to/from the filebucket"
def head(request)
session = Puppet.lookup(:http_session)
api = session.route_to(:puppet)
api.head_filebucket_file(
request.key,
environment: request.environment.to_s,
bucket_path: request.options[:bucket_path]
)
rescue Puppet::HTTP::ResponseError => e
return nil if e.response.code == 404
raise convert_to_http_error(e.response)
end
def find(request)
session = Puppet.lookup(:http_session)
api = session.route_to(:puppet)
_, filebucket_file = api.get_filebucket_file(
request.key,
environment: request.environment.to_s,
bucket_path: request.options[:bucket_path],
diff_with: request.options[:diff_with],
list_all: request.options[:list_all],
fromdate: request.options[:fromdate],
todate: request.options[:todate]
)
filebucket_file
rescue Puppet::HTTP::ResponseError => e
raise convert_to_http_error(e.response)
end
def save(request)
session = Puppet.lookup(:http_session)
api = session.route_to(:puppet)
api.put_filebucket_file(
request.key,
body: request.instance.render,
environment: request.environment.to_s
)
rescue Puppet::HTTP::ResponseError => e
raise convert_to_http_error(e.response)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/file_bucket_file/file.rb | lib/puppet/indirector/file_bucket_file/file.rb | # frozen_string_literal: true
require_relative '../../../puppet/indirector/code'
require_relative '../../../puppet/file_bucket/file'
require_relative '../../../puppet/util/checksums'
require_relative '../../../puppet/util/diff'
require 'fileutils'
module Puppet::FileBucketFile
class File < Puppet::Indirector::Code
include Puppet::Util::Checksums
include Puppet::Util::Diff
desc "Store files in a directory set based on their checksums."
def find(request)
request.options[:bucket_path] ||= Puppet[:bucketdir]
# If filebucket mode is 'list'
if request.options[:list_all]
return nil unless ::File.exist?(request.options[:bucket_path])
return list(request)
end
checksum, files_original_path = request_to_checksum_and_path(request)
contents_file = path_for(request.options[:bucket_path], checksum, 'contents')
paths_file = path_for(request.options[:bucket_path], checksum, 'paths')
if Puppet::FileSystem.exist?(contents_file) && matches(paths_file, files_original_path)
if request.options[:diff_with]
other_contents_file = path_for(request.options[:bucket_path], request.options[:diff_with], 'contents')
raise _("could not find diff_with %{diff}") % { diff: request.options[:diff_with] } unless Puppet::FileSystem.exist?(other_contents_file)
raise _("Unable to diff on this platform") unless Puppet[:diff] != ""
diff(Puppet::FileSystem.path_string(contents_file), Puppet::FileSystem.path_string(other_contents_file))
else
# TRANSLATORS "FileBucket" should not be translated
Puppet.info _("FileBucket read %{checksum}") % { checksum: checksum }
model.new(Puppet::FileSystem.binread(contents_file))
end
else
nil
end
end
def list(request)
if request.remote?
raise Puppet::Error, _("Listing remote file buckets is not allowed")
end
fromdate = request.options[:fromdate] || "0:0:0 1-1-1970"
todate = request.options[:todate] || Time.now.strftime("%F %T")
begin
to = Time.parse(todate)
rescue ArgumentError
raise Puppet::Error, _("Error while parsing 'todate'")
end
begin
from = Time.parse(fromdate)
rescue ArgumentError
raise Puppet::Error, _("Error while parsing 'fromdate'")
end
# Setting hash's default value to [], needed by the following loop
bucket = Hash.new { [] }
msg = ''.dup
# Get all files with mtime between 'from' and 'to'
Pathname.new(request.options[:bucket_path]).find { |item|
next unless item.file? and item.basename.to_s == "paths"
filenames = item.read.strip.split("\n")
filestat = Time.parse(item.stat.mtime.to_s)
next unless from <= filestat and filestat <= to
filenames.each do |filename|
bucket[filename] += [[item.stat.mtime, item.parent.basename]]
end
}
# Sort the results
bucket.each { |_filename, contents|
contents.sort_by! do |item|
# NOTE: Ruby 2.4 may reshuffle item order even if the keys in sequence are sorted already
item[0]
end
}
# Build the output message. Sorted by names then by dates
bucket.sort.each { |filename, contents|
contents.each { |mtime, chksum|
date = mtime.strftime("%F %T")
msg += "#{chksum} #{date} #{filename}\n"
}
}
model.new(msg)
end
def head(request)
checksum, files_original_path = request_to_checksum_and_path(request)
contents_file = path_for(request.options[:bucket_path], checksum, 'contents')
paths_file = path_for(request.options[:bucket_path], checksum, 'paths')
Puppet::FileSystem.exist?(contents_file) && matches(paths_file, files_original_path)
end
def save(request)
instance = request.instance
_, files_original_path = request_to_checksum_and_path(request)
contents_file = path_for(instance.bucket_path, instance.checksum_data, 'contents')
paths_file = path_for(instance.bucket_path, instance.checksum_data, 'paths')
save_to_disk(instance, files_original_path, contents_file, paths_file)
# don't echo the request content back to the agent
model.new('')
end
def validate_key(request)
# There are no ACLs on filebucket files so validating key is not important
end
private
# @param paths_file [Object] Opaque file path
# @param files_original_path [String]
#
def matches(paths_file, files_original_path)
# Puppet will have already written the paths_file in the systems encoding
# given its possible that request.options[:bucket_path] or Puppet[:bucketdir]
# contained characters in an encoding that are not represented the
# same way when the bytes are decoded as UTF-8, continue using system encoding
Puppet::FileSystem.open(paths_file, 0o640, 'a+:external') do |f|
path_match(f, files_original_path)
end
end
def path_match(file_handle, files_original_path)
return true unless files_original_path # if no path was provided, it's a match
file_handle.rewind
file_handle.each_line do |line|
return true if line.chomp == files_original_path
end
false
end
# @param bucket_file [Puppet::FileBucket::File] IO object representing
# content to back up
# @param files_original_path [String] Path to original source file on disk
# @param contents_file [Pathname] Opaque file path to intended backup
# location
# @param paths_file [Pathname] Opaque file path to file containing source
# file paths on disk
# @return [void]
# @raise [Puppet::FileBucket::BucketError] on possible sum collision between
# existing and new backup
# @api private
def save_to_disk(bucket_file, files_original_path, contents_file, paths_file)
Puppet::Util.withumask(0o007) do
unless Puppet::FileSystem.dir_exist?(paths_file)
Puppet::FileSystem.dir_mkpath(paths_file)
end
# Puppet will have already written the paths_file in the systems encoding
# given its possible that request.options[:bucket_path] or Puppet[:bucketdir]
# contained characters in an encoding that are not represented the
# same way when the bytes are decoded as UTF-8, continue using system encoding
Puppet::FileSystem.exclusive_open(paths_file, 0o640, 'a+:external') do |f|
if Puppet::FileSystem.exist?(contents_file)
if verify_identical_file(contents_file, bucket_file)
# TRANSLATORS "FileBucket" should not be translated
Puppet.info _("FileBucket got a duplicate file %{file_checksum}") % { file_checksum: bucket_file.checksum }
# Don't touch the contents file on Windows, since we can't update the
# mtime of read-only files there.
unless Puppet::Util::Platform.windows?
Puppet::FileSystem.touch(contents_file)
end
elsif contents_file_matches_checksum?(contents_file, bucket_file.checksum_data, bucket_file.checksum_type)
# If the contents or sizes don't match, but the checksum does,
# then we've found a conflict (potential hash collision).
# Unlikely, but quite bad. Don't remove the file in case it's
# needed, but ask the user to validate.
# Note: Don't print the full path to the bucket file in the
# exception to avoid disclosing file system layout on server.
# TRANSLATORS "FileBucket" should not be translated
Puppet.err(_("Unable to verify existing FileBucket backup at '%{path}'.") % { path: contents_file.to_path })
raise Puppet::FileBucket::BucketError, _("Existing backup and new file have different content but same checksum, %{value}. Verify existing backup and remove if incorrect.") %
{ value: bucket_file.checksum }
else
# PUP-1334 If the contents_file exists but does not match its
# checksum, our backup has been corrupted. Warn about overwriting
# it, and proceed with new backup.
Puppet.warning(_("Existing backup does not match its expected sum, %{sum}. Overwriting corrupted backup.") % { sum: bucket_file.checksum })
copy_bucket_file_to_contents_file(contents_file, bucket_file)
end
else
copy_bucket_file_to_contents_file(contents_file, bucket_file)
end
unless path_match(f, files_original_path)
f.seek(0, IO::SEEK_END)
f.puts(files_original_path)
end
end
end
end
def request_to_checksum_and_path(request)
checksum_type, checksum, path = request.key.split(%r{/}, 3)
if path == '' # Treat "md5/<checksum>/" like "md5/<checksum>"
path = nil
end
raise ArgumentError, _("Unsupported checksum type %{checksum_type}") % { checksum_type: checksum_type.inspect } if checksum_type != Puppet[:digest_algorithm]
expected = method(checksum_type + "_hex_length").call
raise _("Invalid checksum %{checksum}") % { checksum: checksum.inspect } if checksum !~ /^[0-9a-f]{#{expected}}$/
[checksum, path]
end
# @return [Object] Opaque path as constructed by the Puppet::FileSystem
#
def path_for(bucket_path, digest, subfile = nil)
bucket_path ||= Puppet[:bucketdir]
dir = ::File.join(digest[0..7].split(""))
basedir = ::File.join(bucket_path, dir, digest)
Puppet::FileSystem.pathname(subfile ? ::File.join(basedir, subfile) : basedir)
end
# @param contents_file [Pathname] Opaque file path to intended backup
# location
# @param bucket_file [Puppet::FileBucket::File] IO object representing
# content to back up
# @return [Boolean] whether the data in contents_file is of the same size
# and content as that in the bucket_file
# @api private
def verify_identical_file(contents_file, bucket_file)
(bucket_file.to_binary.bytesize == Puppet::FileSystem.size(contents_file)) &&
bucket_file.stream() { |s| Puppet::FileSystem.compare_stream(contents_file, s) }
end
# @param contents_file [Pathname] Opaque file path to intended backup
# location
# @param expected_checksum_data [String] expected value of checksum of type
# checksum_type
# @param checksum_type [String] type of check sum of checksum_data, ie "md5"
# @return [Boolean] whether the checksum of the contents_file matches the
# supplied checksum
# @api private
def contents_file_matches_checksum?(contents_file, expected_checksum_data, checksum_type)
contents_file_checksum_data = Puppet::Util::Checksums.method(:"#{checksum_type}_file").call(contents_file.to_path)
contents_file_checksum_data == expected_checksum_data
end
# @param contents_file [Pathname] Opaque file path to intended backup
# location
# @param bucket_file [Puppet::FileBucket::File] IO object representing
# content to back up
# @return [void]
# @api private
def copy_bucket_file_to_contents_file(contents_file, bucket_file)
Puppet::FileSystem.replace_file(contents_file, 0o440) do |of|
# PUP-1044 writes all of the contents
bucket_file.stream() do |src|
FileUtils.copy_stream(src, of)
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/issues.rb | lib/puppet/pops/issues.rb | # frozen_string_literal: true
# Defines classes to deal with issues, and message formatting and defines constants with Issues.
# @api public
#
module Puppet::Pops
module Issues
# Describes an issue, and can produce a message for an occurrence of the issue.
#
class Issue
# The issue code
# @return [Symbol]
attr_reader :issue_code
# A block producing the message
# @return [Proc]
attr_reader :message_block
# Names that must be bound in an occurrence of the issue to be able to produce a message.
# These are the names in addition to requirements stipulated by the Issue formatter contract; i.e. :label`,
# and `:semantic`.
#
attr_reader :arg_names
# If this issue can have its severity lowered to :warning, :deprecation, or :ignored
attr_writer :demotable
# Configures the Issue with required arguments (bound by occurrence), and a block producing a message.
def initialize issue_code, *args, &block
@issue_code = issue_code
@message_block = block
@arg_names = args
@demotable = true
end
# Returns true if it is allowed to demote this issue
def demotable?
@demotable
end
# Formats a message for an occurrence of the issue with argument bindings passed in a hash.
# The hash must contain a LabelProvider bound to the key `label` and the semantic model element
# bound to the key `semantic`. All required arguments as specified by `arg_names` must be bound
# in the given `hash`.
# @api public
#
def format(hash = {})
# Create a Message Data where all hash keys become methods for convenient interpolation
# in issue text.
msgdata = MessageData.new(*arg_names)
begin
# Evaluate the message block in the msg data's binding
msgdata.format(hash, &message_block)
rescue StandardError => e
raise RuntimeError, _("Error while reporting issue: %{code}. %{message}") % { code: issue_code, message: e.message }, caller
end
end
end
# Provides a binding of arguments passed to Issue.format to method names available
# in the issue's message producing block.
# @api private
#
class MessageData
def initialize *argnames
singleton = class << self; self end
argnames.each do |name|
singleton.send(:define_method, name) do
@data[name]
end
end
end
def format(hash, &block)
@data = hash
instance_eval(&block)
end
# Obtains the label provider given as a key `:label` in the hash passed to #format. The label provider is
# return if no arguments are given. If given an argument, returns the result of calling #label on the label
# provider.
#
# @param args [Object] one object to obtain a label for or zero arguments to obtain the label provider
# @return [LabelProvider,String] the label provider or label depending on if an argument is given or not
# @raise [Puppet::Error] if no label provider is found
def label(*args)
args.empty? ? label_provider : label_provider.label(args[0])
end
# Returns the label provider given as key `:label` in the hash passed to #format.
# @return [LabelProvider] the label provider
# @raise [Puppet::Error] if no label provider is found
def label_provider
label_provider = @data[:label]
# TRANSLATORS ":label" is a keyword and should not be translated
raise Puppet::Error, _('Label provider key :label must be set to produce the text of the message!') unless label_provider
label_provider
end
# Returns the label provider given as a key in the hash passed to #format.
#
def semantic
# TRANSLATORS ":semantic" is a keyword and should not be translated
raise Puppet::Error, _('Label provider key :semantic must be set to produce the text of the message!') unless @data[:semantic]
@data[:semantic]
end
end
# Defines an issue with the given `issue_code`, additional required parameters, and a block producing a message.
# The block is evaluated in the context of a MessageData which provides convenient access to all required arguments
# via accessor methods. In addition to accessors for specified arguments, these are also available:
# * `label` - a `LabelProvider` that provides human understandable names for model elements and production of article (a/an/the).
# * `semantic` - the model element for which the issue is reported
#
# @param issue_code [Symbol] the issue code for the issue used as an identifier, should be the same as the constant
# the issue is bound to.
# @param args [Symbol] required arguments that must be passed when formatting the message, may be empty
# @param block [Proc] a block producing the message string, evaluated in a MessageData scope. The produced string
# should not end with a period as additional information may be appended.
#
# @see MessageData
# @api public
#
def self.issue(issue_code, *args, &block)
Issue.new(issue_code, *args, &block)
end
# Creates a non demotable issue.
# @see Issue.issue
#
def self.hard_issue(issue_code, *args, &block)
result = Issue.new(issue_code, *args, &block)
result.demotable = false
result
end
# @comment Here follows definitions of issues. The intent is to provide a list from which yardoc can be generated
# containing more detailed information / explanation of the issue.
# These issues are set as constants, but it is unfortunately not possible for the created object to easily know which
# name it is bound to. Instead the constant has to be repeated. (Alternatively, it could be done by instead calling
# #const_set on the module, but the extra work required to get yardoc output vs. the extra effort to repeat the name
# twice makes it not worth it (if doable at all, since there is no tag to artificially construct a constant, and
# the parse tag does not produce any result for a constant assignment).
# This is allowed (3.1) and has not yet been deprecated.
# @todo configuration
#
NAME_WITH_HYPHEN = issue :NAME_WITH_HYPHEN, :name do
_("%{issue} may not have a name containing a hyphen. The name '%{name}' is not legal") % { issue: label.a_an_uc(semantic), name: name }
end
# When a variable name contains a hyphen and these are illegal.
# It is possible to control if a hyphen is legal in a name or not using the setting TODO
# @todo describe the setting
# @api public
# @todo configuration if this is error or warning
#
VAR_WITH_HYPHEN = issue :VAR_WITH_HYPHEN, :name do
_("A variable name may not contain a hyphen. The name '%{name}' is not legal") % { name: name }
end
# A class, definition, or node may only appear at top level or inside other classes
# @todo Is this really true for nodes? Can they be inside classes? Isn't that too late?
# @api public
#
NOT_TOP_LEVEL = hard_issue :NOT_TOP_LEVEL do
_("Classes, definitions, and nodes may only appear at toplevel or inside other classes")
end
NOT_ABSOLUTE_TOP_LEVEL = hard_issue :NOT_ABSOLUTE_TOP_LEVEL do
_("%{value} may only appear at toplevel") % { value: label.a_an_uc(semantic) }
end
CROSS_SCOPE_ASSIGNMENT = hard_issue :CROSS_SCOPE_ASSIGNMENT, :name do
_("Illegal attempt to assign to '%{name}'. Cannot assign to variables in other namespaces") % { name: name }
end
# Assignment can only be made to certain types of left hand expressions such as variables.
ILLEGAL_ASSIGNMENT = hard_issue :ILLEGAL_ASSIGNMENT do
_("Illegal attempt to assign to '%{value}'. Not an assignable reference") % { value: label.a_an(semantic) }
end
# Variables are immutable, cannot reassign in the same assignment scope
ILLEGAL_REASSIGNMENT = hard_issue :ILLEGAL_REASSIGNMENT, :name do
if Validation::Checker4_0::RESERVED_PARAMETERS[name]
_("Cannot reassign built in (or already assigned) variable '$%{var}'") % { var: name }
else
_("Cannot reassign variable '$%{var}'") % { var: name }
end
end
# Variables facts and trusted
ILLEGAL_RESERVED_ASSIGNMENT = hard_issue :ILLEGAL_RESERVED_ASSIGNMENT, :name do
_("Attempt to assign to a reserved variable name: '$%{var}'") % { var: name }
end
# Assignment cannot be made to numeric match result variables
ILLEGAL_NUMERIC_ASSIGNMENT = issue :ILLEGAL_NUMERIC_ASSIGNMENT, :varname do
_("Illegal attempt to assign to the numeric match result variable '$%{var}'. Numeric variables are not assignable") % { var: varname }
end
# Assignment can only be made to certain types of left hand expressions such as variables.
ILLEGAL_ASSIGNMENT_CONTEXT = hard_issue :ILLEGAL_ASSIGNMENT_CONTEXT do
_("Assignment not allowed here")
end
# parameters cannot have numeric names, clashes with match result variables
ILLEGAL_NUMERIC_PARAMETER = issue :ILLEGAL_NUMERIC_PARAMETER, :name do
_("The numeric parameter name '$%{name}' cannot be used (clashes with numeric match result variables)") % { name: name }
end
ILLEGAL_NONLITERAL_PARAMETER_TYPE = issue :ILLEGAL_NONLITERAL_PARAMETER_TYPE, :name, :type_class do
_("The parameter '$%{name}' must be a literal type, not %{type_class}") % { name: name, type_class: label.a_an(type_class) }
end
# In certain versions of Puppet it may be allowed to assign to a not already assigned key
# in an array or a hash. This is an optional validation that may be turned on to prevent accidental
# mutation.
#
ILLEGAL_INDEXED_ASSIGNMENT = issue :ILLEGAL_INDEXED_ASSIGNMENT do
_("Illegal attempt to assign via [index/key]. Not an assignable reference")
end
# When indexed assignment ($x[]=) is allowed, the leftmost expression must be
# a variable expression.
#
ILLEGAL_ASSIGNMENT_VIA_INDEX = hard_issue :ILLEGAL_ASSIGNMENT_VIA_INDEX do
_("Illegal attempt to assign to %{value} via [index/key]. Not an assignable reference") % { value: label.a_an(semantic) }
end
ILLEGAL_MULTI_ASSIGNMENT_SIZE = hard_issue :ILLEGAL_MULTI_ASSIGNMENT_SIZE, :expected, :actual do
_("Mismatched number of assignable entries and values, expected %{expected}, got %{actual}") % { expected: expected, actual: actual }
end
MISSING_MULTI_ASSIGNMENT_KEY = hard_issue :MISSING_MULTI_ASSIGNMENT_KEY, :key do
_("No value for required key '%{key}' in assignment to variables from hash") % { key: key }
end
MISSING_MULTI_ASSIGNMENT_VARIABLE = hard_issue :MISSING_MULTI_ASSIGNMENT_VARIABLE, :name do
_("No value for required variable '$%{name}' in assignment to variables from class reference") % { name: name }
end
APPENDS_DELETES_NO_LONGER_SUPPORTED = hard_issue :APPENDS_DELETES_NO_LONGER_SUPPORTED, :operator do
_("The operator '%{operator}' is no longer supported. See http://links.puppet.com/remove-plus-equals") % { operator: operator }
end
# For unsupported operators (e.g. += and -= in puppet 4).
#
UNSUPPORTED_OPERATOR = hard_issue :UNSUPPORTED_OPERATOR, :operator do
_("The operator '%{operator}' is not supported.") % { operator: operator }
end
# For operators that are not supported in specific contexts (e.g. '* =>' in
# resource defaults)
#
UNSUPPORTED_OPERATOR_IN_CONTEXT = hard_issue :UNSUPPORTED_OPERATOR_IN_CONTEXT, :operator do
_("The operator '%{operator}' in %{value} is not supported.") % { operator: operator, value: label.a_an(semantic) }
end
# For non applicable operators (e.g. << on Hash).
#
OPERATOR_NOT_APPLICABLE = hard_issue :OPERATOR_NOT_APPLICABLE, :operator, :left_value do
_("Operator '%{operator}' is not applicable to %{left}.") % { operator: operator, left: label.a_an(left_value) }
end
OPERATOR_NOT_APPLICABLE_WHEN = hard_issue :OPERATOR_NOT_APPLICABLE_WHEN, :operator, :left_value, :right_value do
_("Operator '%{operator}' is not applicable to %{left} when right side is %{right}.") % { operator: operator, left: label.a_an(left_value), right: label.a_an(right_value) }
end
COMPARISON_NOT_POSSIBLE = hard_issue :COMPARISON_NOT_POSSIBLE, :operator, :left_value, :right_value, :detail do
_("Comparison of: %{left} %{operator} %{right}, is not possible. Caused by '%{detail}'.") % { left: label(left_value), operator: operator, right: label(right_value), detail: detail }
end
MATCH_NOT_REGEXP = hard_issue :MATCH_NOT_REGEXP, :detail do
_("Can not convert right match operand to a regular expression. Caused by '%{detail}'.") % { detail: detail }
end
MATCH_NOT_STRING = hard_issue :MATCH_NOT_STRING, :left_value do
_("Left match operand must result in a String value. Got %{left}.") % { left: label.a_an(left_value) }
end
# Some expressions/statements may not produce a value (known as right-value, or rvalue).
# This may vary between puppet versions.
#
NOT_RVALUE = issue :NOT_RVALUE do
_("Invalid use of expression. %{value} does not produce a value") % { value: label.a_an_uc(semantic) }
end
# Appending to attributes is only allowed in certain types of resource expressions.
#
ILLEGAL_ATTRIBUTE_APPEND = hard_issue :ILLEGAL_ATTRIBUTE_APPEND, :name, :parent do
_("Illegal +> operation on attribute %{attr}. This operator can not be used in %{expression}") % { attr: name, expression: label.a_an(parent) }
end
ILLEGAL_NAME = hard_issue :ILLEGAL_NAME, :name do
_("Illegal name. The given name '%{name}' does not conform to the naming rule /^((::)?[a-z_]\\w*)(::[a-z]\\w*)*$/") % { name: name }
end
ILLEGAL_SINGLE_TYPE_MAPPING = hard_issue :ILLEGAL_TYPE_MAPPING, :expression do
_("Illegal type mapping. Expected a Type on the left side, got %{expression}") % { expression: label.a_an_uc(semantic) }
end
ILLEGAL_REGEXP_TYPE_MAPPING = hard_issue :ILLEGAL_TYPE_MAPPING, :expression do
_("Illegal type mapping. Expected a Tuple[Regexp,String] on the left side, got %{expression}") % { expression: label.a_an_uc(semantic) }
end
ILLEGAL_PARAM_NAME = hard_issue :ILLEGAL_PARAM_NAME, :name do
_("Illegal parameter name. The given name '%{name}' does not conform to the naming rule /^[a-z_]\\w*$/") % { name: name }
end
ILLEGAL_VAR_NAME = hard_issue :ILLEGAL_VAR_NAME, :name do
_("Illegal variable name, The given name '%{name}' does not conform to the naming rule /^((::)?[a-z]\\w*)*((::)?[a-z_]\\w*)$/") % { name: name }
end
ILLEGAL_NUMERIC_VAR_NAME = hard_issue :ILLEGAL_NUMERIC_VAR_NAME, :name do
_("Illegal numeric variable name, The given name '%{name}' must be a decimal value if it starts with a digit 0-9") % { name: name }
end
# In case a model is constructed programmatically, it must create valid type references.
#
ILLEGAL_CLASSREF = hard_issue :ILLEGAL_CLASSREF, :name do
_("Illegal type reference. The given name '%{name}' does not conform to the naming rule") % { name: name }
end
# This is a runtime issue - storeconfigs must be on in order to collect exported. This issue should be
# set to :ignore when just checking syntax.
# @todo should be a :warning by default
#
RT_NO_STORECONFIGS = issue :RT_NO_STORECONFIGS do
_("You cannot collect exported resources without storeconfigs being set; the collection will be ignored")
end
# This is a runtime issue - storeconfigs must be on in order to export a resource. This issue should be
# set to :ignore when just checking syntax.
# @todo should be a :warning by default
#
RT_NO_STORECONFIGS_EXPORT = issue :RT_NO_STORECONFIGS_EXPORT do
_("You cannot collect exported resources without storeconfigs being set; the export is ignored")
end
# A hostname may only contain letters, digits, '_', '-', and '.'.
#
ILLEGAL_HOSTNAME_CHARS = hard_issue :ILLEGAL_HOSTNAME_CHARS, :hostname do
_("The hostname '%{hostname}' contains illegal characters (only letters, digits, '_', '-', and '.' are allowed)") % { hostname: hostname }
end
# A hostname may only contain letters, digits, '_', '-', and '.'.
#
ILLEGAL_HOSTNAME_INTERPOLATION = hard_issue :ILLEGAL_HOSTNAME_INTERPOLATION do
_("An interpolated expression is not allowed in a hostname of a node")
end
# Issues when an expression is used where it is not legal.
# E.g. an arithmetic expression where a hostname is expected.
#
ILLEGAL_EXPRESSION = hard_issue :ILLEGAL_EXPRESSION, :feature, :container do
_("Illegal expression. %{expression} is unacceptable as %{feature} in %{container}") % { expression: label.a_an_uc(semantic), feature: feature, container: label.a_an(container) }
end
# Issues when a variable is not a NAME
#
ILLEGAL_VARIABLE_EXPRESSION = hard_issue :ILLEGAL_VARIABLE_EXPRESSION do
_("Illegal variable expression. %{expression} did not produce a variable name (String or Numeric).") % { expression: label.a_an_uc(semantic) }
end
# Issues when an expression is used illegally in a query.
# query only supports == and !=, and not <, > etc.
#
ILLEGAL_QUERY_EXPRESSION = hard_issue :ILLEGAL_QUERY_EXPRESSION do
_("Illegal query expression. %{expression} cannot be used in a query") % { expression: label.a_an_uc(semantic) }
end
# If an attempt is made to make a resource default virtual or exported.
#
NOT_VIRTUALIZEABLE = hard_issue :NOT_VIRTUALIZEABLE do
_("Resource Defaults are not virtualizable")
end
CLASS_NOT_VIRTUALIZABLE = issue :CLASS_NOT_VIRTUALIZABLE do
_("Classes are not virtualizable")
end
# When an attempt is made to use multiple keys (to produce a range in Ruby - e.g. $arr[2,-1]).
# This is not supported in 3x, but it allowed in 4x.
#
UNSUPPORTED_RANGE = issue :UNSUPPORTED_RANGE, :count do
_("Attempt to use unsupported range in %{expression}, %{count} values given for max 1") % { expression: label.a_an(semantic), count: count }
end
# Issues when expressions that are not implemented or activated in the current version are used.
#
UNSUPPORTED_EXPRESSION = issue :UNSUPPORTED_EXPRESSION do
_("Expressions of type %{expression} are not supported in this version of Puppet") % { expression: label.a_an(semantic) }
end
ILLEGAL_RELATIONSHIP_OPERAND_TYPE = issue :ILLEGAL_RELATIONSHIP_OPERAND_TYPE, :operand do
_("Illegal relationship operand, can not form a relationship with %{expression}. A Catalog type is required.") % { expression: label.a_an(operand) }
end
NOT_CATALOG_TYPE = issue :NOT_CATALOG_TYPE, :type do
_("Illegal relationship operand, can not form a relationship with something of type %{expression_type}. A Catalog type is required.") % { expression_type: type }
end
BAD_STRING_SLICE_ARITY = issue :BAD_STRING_SLICE_ARITY, :actual do
_("String supports [] with one or two arguments. Got %{actual}") % { actual: actual }
end
BAD_STRING_SLICE_TYPE = issue :BAD_STRING_SLICE_TYPE, :actual do
_("String-Type [] requires all arguments to be integers (or default). Got %{actual}") % { actual: actual }
end
BAD_ARRAY_SLICE_ARITY = issue :BAD_ARRAY_SLICE_ARITY, :actual do
_("Array supports [] with one or two arguments. Got %{actual}") % { actual: actual }
end
BAD_HASH_SLICE_ARITY = issue :BAD_HASH_SLICE_ARITY, :actual do
_("Hash supports [] with one or more arguments. Got %{actual}") % { actual: actual }
end
BAD_INTEGER_SLICE_ARITY = issue :BAD_INTEGER_SLICE_ARITY, :actual do
_("Integer-Type supports [] with one or two arguments (from, to). Got %{actual}") % { actual: actual }
end
BAD_INTEGER_SLICE_TYPE = issue :BAD_INTEGER_SLICE_TYPE, :actual do
_("Integer-Type [] requires all arguments to be integers (or default). Got %{actual}") % { actual: actual }
end
BAD_COLLECTION_SLICE_TYPE = issue :BAD_COLLECTION_SLICE_TYPE, :actual do
_("A Type's size constraint arguments must be a single Integer type, or 1-2 integers (or default). Got %{actual}") % { actual: label.a_an(actual) }
end
BAD_FLOAT_SLICE_ARITY = issue :BAD_INTEGER_SLICE_ARITY, :actual do
_("Float-Type supports [] with one or two arguments (from, to). Got %{actual}") % { actual: actual }
end
BAD_FLOAT_SLICE_TYPE = issue :BAD_INTEGER_SLICE_TYPE, :actual do
_("Float-Type [] requires all arguments to be floats, or integers (or default). Got %{actual}") % { actual: actual }
end
BAD_SLICE_KEY_TYPE = issue :BAD_SLICE_KEY_TYPE, :left_value, :expected_classes, :actual do
if expected_classes.size > 1
_("%{expression}[] cannot use %{actual} where one of the following is expected: %{expected}") % { expression: label.a_an_uc(left_value), actual: actual, expected: expected_classes.join(', ') }
else
_("%{expression}[] cannot use %{actual} where %{expected} is expected") % { expression: label.a_an_uc(left_value), actual: actual, expected: expected_classes[0] }
end
end
BAD_STRING_SLICE_KEY_TYPE = issue :BAD_STRING_SLICE_KEY_TYPE, :left_value, :actual_type do
_("A substring operation does not accept %{label_article} %{actual_type} as a character index. Expected an Integer") % { label_article: label.article(actual_type), actual_type: actual_type }
end
BAD_NOT_UNDEF_SLICE_TYPE = issue :BAD_NOT_UNDEF_SLICE_TYPE, :base_type, :actual do
_("%{expression}[] argument must be a Type or a String. Got %{actual}") % { expression: base_type, actual: actual }
end
BAD_TYPE_SLICE_TYPE = issue :BAD_TYPE_SLICE_TYPE, :base_type, :actual do
_("%{base_type}[] arguments must be types. Got %{actual}") % { base_type: base_type, actual: actual }
end
BAD_TYPE_SLICE_ARITY = issue :BAD_TYPE_SLICE_ARITY, :base_type, :min, :max, :actual do
base_type_label = base_type.is_a?(String) ? base_type : label.a_an_uc(base_type)
if max == -1 || max == Float::INFINITY
_("%{base_type_label}[] accepts %{min} or more arguments. Got %{actual}") % { base_type_label: base_type_label, min: min, actual: actual }
elsif max && max != min
_("%{base_type_label}[] accepts %{min} to %{max} arguments. Got %{actual}") % { base_type_label: base_type_label, min: min, max: max, actual: actual }
else
_("%{base_type_label}[] accepts %{min} %{label}. Got %{actual}") % { base_type_label: base_type_label, min: min, label: label.plural_s(min, _('argument')), actual: actual }
end
end
BAD_TYPE_SPECIALIZATION = hard_issue :BAD_TYPE_SPECIALIZATION, :type, :message do
_("Error creating type specialization of %{base_type}, %{message}") % { base_type: label.a_an(type), message: message }
end
ILLEGAL_TYPE_SPECIALIZATION = issue :ILLEGAL_TYPE_SPECIALIZATION, :kind do
_("Cannot specialize an already specialized %{kind} type") % { kind: kind }
end
ILLEGAL_RESOURCE_SPECIALIZATION = issue :ILLEGAL_RESOURCE_SPECIALIZATION, :actual do
_("First argument to Resource[] must be a resource type or a String. Got %{actual}.") % { actual: actual }
end
EMPTY_RESOURCE_SPECIALIZATION = issue :EMPTY_RESOURCE_SPECIALIZATION do
_("Arguments to Resource[] are all empty/undefined")
end
ILLEGAL_HOSTCLASS_NAME = hard_issue :ILLEGAL_HOSTCLASS_NAME, :name do
_("Illegal Class name in class reference. %{expression} cannot be used where a String is expected") % { expression: label.a_an_uc(name) }
end
ILLEGAL_DEFINITION_NAME = hard_issue :ILLEGAL_DEFINITION_NAME, :name do
_("Unacceptable name. The name '%{name}' is unacceptable as the name of %{value}") % { name: name, value: label.a_an(semantic) }
end
ILLEGAL_DEFINITION_LOCATION = issue :ILLEGAL_DEFINITION_LOCATION, :name, :file do
_("Unacceptable location. The name '%{name}' is unacceptable in file '%{file}'") % { name: name, file: file }
end
ILLEGAL_TOP_CONSTRUCT_LOCATION = issue :ILLEGAL_TOP_CONSTRUCT_LOCATION do
if semantic.is_a?(Puppet::Pops::Model::NamedDefinition)
_("The %{value} '%{name}' is unacceptable as a top level construct in this location") % { name: semantic.name, value: label(semantic) }
else
_("This %{value} is unacceptable as a top level construct in this location") % { value: label(semantic) }
end
end
CAPTURES_REST_NOT_LAST = hard_issue :CAPTURES_REST_NOT_LAST, :param_name do
_("Parameter $%{param} is not last, and has 'captures rest'") % { param: param_name }
end
CAPTURES_REST_NOT_SUPPORTED = hard_issue :CAPTURES_REST_NOT_SUPPORTED, :container, :param_name do
_("Parameter $%{param} has 'captures rest' - not supported in %{container}") % { param: param_name, container: label.a_an(container) }
end
REQUIRED_PARAMETER_AFTER_OPTIONAL = hard_issue :REQUIRED_PARAMETER_AFTER_OPTIONAL, :param_name do
_("Parameter $%{param} is required but appears after optional parameters") % { param: param_name }
end
MISSING_REQUIRED_PARAMETER = hard_issue :MISSING_REQUIRED_PARAMETER, :param_name do
_("Parameter $%{param} is required but no value was given") % { param: param_name }
end
NOT_NUMERIC = issue :NOT_NUMERIC, :value do
_("The value '%{value}' cannot be converted to Numeric.") % { value: value }
end
NUMERIC_COERCION = issue :NUMERIC_COERCION, :before, :after do
_("The string '%{before}' was automatically coerced to the numerical value %{after}") % { before: before, after: after }
end
UNKNOWN_FUNCTION = issue :UNKNOWN_FUNCTION, :name do
_("Unknown function: '%{name}'.") % { name: name }
end
UNKNOWN_VARIABLE = issue :UNKNOWN_VARIABLE, :name do
_("Unknown variable: '%{name}'.") % { name: name }
end
RUNTIME_ERROR = issue :RUNTIME_ERROR, :detail do
_("Error while evaluating %{expression}, %{detail}") % { expression: label.a_an(semantic), detail: detail }
end
UNKNOWN_RESOURCE_TYPE = issue :UNKNOWN_RESOURCE_TYPE, :type_name do
_("Resource type not found: %{res_type}") % { res_type: type_name }
end
ILLEGAL_RESOURCE_TYPE = hard_issue :ILLEGAL_RESOURCE_TYPE, :actual do
_("Illegal Resource Type expression, expected result to be a type name, or untitled Resource, got %{actual}") % { actual: actual }
end
DUPLICATE_TITLE = issue :DUPLICATE_TITLE, :title do
_("The title '%{title}' has already been used in this resource expression") % { title: title }
end
DUPLICATE_ATTRIBUTE = issue :DUPLICATE_ATTRIBUE, :attribute do
_("The attribute '%{attribute}' has already been set") % { attribute: attribute }
end
MISSING_TITLE = hard_issue :MISSING_TITLE do
_("Missing title. The title expression resulted in undef")
end
MISSING_TITLE_AT = hard_issue :MISSING_TITLE_AT, :index do
_("Missing title at index %{index}. The title expression resulted in an undef title") % { index: index }
end
ILLEGAL_TITLE_TYPE_AT = hard_issue :ILLEGAL_TITLE_TYPE_AT, :index, :actual do
_("Illegal title type at index %{index}. Expected String, got %{actual}") % { index: index, actual: actual }
end
EMPTY_STRING_TITLE_AT = hard_issue :EMPTY_STRING_TITLE_AT, :index do
_("Empty string title at %{index}. Title strings must have a length greater than zero.") % { index: index }
end
UNKNOWN_RESOURCE = issue :UNKNOWN_RESOURCE, :type_name, :title do
_("Resource not found: %{type_name}['%{title}']") % { type_name: type_name, title: title }
end
UNKNOWN_RESOURCE_PARAMETER = issue :UNKNOWN_RESOURCE_PARAMETER, :type_name, :title, :param_name do
_("The resource %{type_name}['%{title}'] does not have a parameter called '%{param}'") % { type_name: type_name.capitalize, title: title, param: param_name }
end
DIV_BY_ZERO = hard_issue :DIV_BY_ZERO do
_("Division by 0")
end
RESULT_IS_INFINITY = hard_issue :RESULT_IS_INFINITY, :operator do
_("The result of the %{operator} expression is Infinity") % { operator: operator }
end
# TODO_HEREDOC
EMPTY_HEREDOC_SYNTAX_SEGMENT = issue :EMPTY_HEREDOC_SYNTAX_SEGMENT, :syntax do
_("Heredoc syntax specification has empty segment between '+' : '%{syntax}'") % { syntax: syntax }
end
ILLEGAL_EPP_PARAMETERS = issue :ILLEGAL_EPP_PARAMETERS do
_("Ambiguous EPP parameter expression. Probably missing '<%-' before parameters to remove leading whitespace")
end
DISCONTINUED_IMPORT = hard_issue :DISCONTINUED_IMPORT do
# TRANSLATORS "import" is a function name and should not be translated
_("Use of 'import' has been discontinued in favor of a manifest directory. See http://links.puppet.com/puppet-import-deprecation")
end
IDEM_EXPRESSION_NOT_LAST = issue :IDEM_EXPRESSION_NOT_LAST do
_("This %{expression} has no effect. A value was produced and then forgotten (one or more preceding expressions may have the wrong form)") % { expression: label.label(semantic) }
end
RESOURCE_WITHOUT_TITLE = issue :RESOURCE_WITHOUT_TITLE, :name do
_("This expression is invalid. Did you try declaring a '%{name}' resource without a title?") % { name: name }
end
IDEM_NOT_ALLOWED_LAST = hard_issue :IDEM_NOT_ALLOWED_LAST, :container do
_("This %{expression} has no effect. %{container} can not end with a value-producing expression without other effect") % { expression: label.label(semantic), container: label.a_an_uc(container) }
end
RESERVED_WORD = hard_issue :RESERVED_WORD, :word do
_("Use of reserved word: %{word}, must be quoted if intended to be a String value") % { word: word }
end
FUTURE_RESERVED_WORD = issue :FUTURE_RESERVED_WORD, :word do
_("Use of future reserved word: '%{word}'") % { word: word }
end
RESERVED_TYPE_NAME = hard_issue :RESERVED_TYPE_NAME, :name do
_("The name: '%{name}' is already defined by Puppet and can not be used as the name of %{expression}.") % { name: name, expression: label.a_an(semantic) }
end
UNMATCHED_SELECTOR = hard_issue :UNMATCHED_SELECTOR, :param_value do
_("No matching entry for selector parameter with value '%{param}'") % { param: param_value }
end
ILLEGAL_NODE_INHERITANCE = issue :ILLEGAL_NODE_INHERITANCE do
_("Node inheritance is not supported in Puppet >= 4.0.0. See http://links.puppet.com/puppet-node-inheritance-deprecation")
end
ILLEGAL_OVERRIDDEN_TYPE = issue :ILLEGAL_OVERRIDDEN_TYPE, :actual do
_("Resource Override can only operate on resources, got: %{actual}") % { actual: label.label(actual) }
end
DUPLICATE_PARAMETER = hard_issue :DUPLICATE_PARAMETER, :param_name do
_("The parameter '%{param}' is declared more than once in the parameter list") % { param: param_name }
end
DUPLICATE_KEY = issue :DUPLICATE_KEY, :key do
_("The key '%{key}' is declared more than once") % { key: key }
end
DUPLICATE_DEFAULT = hard_issue :DUPLICATE_DEFAULT, :container do
_("This %{container} already has a 'default' entry - this is a duplicate") % { container: label.label(container) }
end
RESERVED_PARAMETER = hard_issue :RESERVED_PARAMETER, :container, :param_name do
_("The parameter $%{param} redefines a built in parameter in %{container}") % { param: param_name, container: label.the(container) }
end
TYPE_MISMATCH = hard_issue :TYPE_MISMATCH, :expected, :actual do
_("Expected value of type %{expected}, got %{actual}") % { expected: expected, actual: actual }
end
MULTIPLE_ATTRIBUTES_UNFOLD = hard_issue :MULTIPLE_ATTRIBUTES_UNFOLD do
_("Unfolding of attributes from Hash can only be used once per resource body")
end
ILLEGAL_CATALOG_RELATED_EXPRESSION = hard_issue :ILLEGAL_CATALOG_RELATED_EXPRESSION do
_("This %{expression} appears in a context where catalog related expressions are not allowed") % { expression: label.label(semantic) }
end
SYNTAX_ERROR = hard_issue :SYNTAX_ERROR, :where do
_("Syntax error at %{location}") % { location: where }
end
ILLEGAL_CLASS_REFERENCE = hard_issue :ILLEGAL_CLASS_REFERENCE do
_('Illegal class reference')
end
ILLEGAL_FULLY_QUALIFIED_CLASS_REFERENCE = hard_issue :ILLEGAL_FULLY_QUALIFIED_CLASS_REFERENCE do
_('Illegal fully qualified class reference')
end
ILLEGAL_FULLY_QUALIFIED_NAME = hard_issue :ILLEGAL_FULLY_QUALIFIED_NAME do
_('Illegal fully qualified name')
end
ILLEGAL_NAME_OR_BARE_WORD = hard_issue :ILLEGAL_NAME_OR_BARE_WORD do
_('Illegal name or bare word')
end
ILLEGAL_NUMBER = hard_issue :ILLEGAL_NUMBER, :value do
_("Illegal number '%{value}'") % { value: value }
end
ILLEGAL_UNICODE_ESCAPE = issue :ILLEGAL_UNICODE_ESCAPE do
_("Unicode escape '\\u' was not followed by 4 hex digits or 1-6 hex digits in {} or was > 10ffff")
end
INVALID_HEX_NUMBER = hard_issue :INVALID_HEX_NUMBER, :value do
_("Not a valid hex number %{value}") % { value: value }
end
INVALID_OCTAL_NUMBER = hard_issue :INVALID_OCTAL_NUMBER, :value do
_("Not a valid octal number %{value}") % { value: value }
end
INVALID_DECIMAL_NUMBER = hard_issue :INVALID_DECIMAL_NUMBER, :value do
_("Not a valid decimal number %{value}") % { value: value }
end
NO_INPUT_TO_LEXER = hard_issue :NO_INPUT_TO_LEXER do
_("Internal Error: No string or file given to lexer to process.")
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/visitable.rb | lib/puppet/pops/visitable.rb | # frozen_string_literal: true
# Visitable is a mix-in module that makes a class visitable by a Visitor
module Puppet::Pops::Visitable
def accept(visitor, *arguments)
visitor.visit(self, *arguments)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/pcore.rb | lib/puppet/pops/pcore.rb | # frozen_string_literal: true
require 'uri'
module Puppet::Pops
module Pcore
include Types::PuppetObject
TYPE_URI_RX = Types::TypeFactory.regexp(URI::DEFAULT_PARSER.make_regexp)
TYPE_URI = Types::TypeFactory.pattern(TYPE_URI_RX)
TYPE_URI_ALIAS = Types::PTypeAliasType.new('Pcore::URI', nil, TYPE_URI)
TYPE_SIMPLE_TYPE_NAME = Types::TypeFactory.pattern(/\A[A-Z]\w*\z/)
TYPE_QUALIFIED_REFERENCE = Types::TypeFactory.pattern(/\A[A-Z]\w*(?:::[A-Z]\w*)*\z/)
TYPE_MEMBER_NAME = Types::PPatternType.new([Types::PRegexpType.new(Patterns::PARAM_NAME)])
KEY_PCORE_URI = 'pcore_uri'
KEY_PCORE_VERSION = 'pcore_version'
PCORE_URI = 'http://puppet.com/2016.1/pcore'
PCORE_VERSION = SemanticPuppet::Version.new(1, 0, 0)
PARSABLE_PCORE_VERSIONS = SemanticPuppet::VersionRange.parse('1.x')
RUNTIME_NAME_AUTHORITY = 'http://puppet.com/2016.1/runtime'
def self._pcore_type
@type
end
def self.annotate(instance, annotations_hash)
annotations_hash.each_pair do |type, init_hash|
type.implementation_class.annotate(instance) { init_hash }
end
instance
end
def self.init_env(loader)
if Puppet[:tasks]
add_object_type('Task', <<-PUPPET, loader)
{
attributes => {
# Fully qualified name of the task
name => { type => Pattern[/\\A[a-z][a-z0-9_]*(?:::[a-z][a-z0-9_]*)*\\z/] },
# List of file references referenced by metadata and their paths on disk.
# If there are no implementations listed in metadata, the first file is always
# the task executable.
files => { type => Array[Struct[name => String, path => String]] },
# Task metadata
metadata => { type => Hash[String, Any] },
# Map parameter names to their parsed data type
parameters => { type => Optional[Hash[Pattern[/\\A[a-z][a-z0-9_]*\\z/], Type]], value => undef },
}
}
PUPPET
end
end
def self.init(loader, ir)
add_alias('Pcore::URI_RX', TYPE_URI_RX, loader)
add_type(TYPE_URI_ALIAS, loader)
add_alias('Pcore::SimpleTypeName', TYPE_SIMPLE_TYPE_NAME, loader)
add_alias('Pcore::MemberName', TYPE_MEMBER_NAME, loader)
add_alias('Pcore::TypeName', TYPE_QUALIFIED_REFERENCE, loader)
add_alias('Pcore::QRef', TYPE_QUALIFIED_REFERENCE, loader)
Types::TypedModelObject.register_ptypes(loader, ir)
@type = create_object_type(loader, ir, Pcore, 'Pcore', nil)
ir.register_implementation_namespace('Pcore', 'Puppet::Pops::Pcore')
ir.register_implementation_namespace('Puppet::AST', 'Puppet::Pops::Model')
ir.register_implementation('Puppet::AST::Locator', 'Puppet::Pops::Parser::Locator::Locator19')
Resource.register_ptypes(loader, ir)
Lookup::Context.register_ptype(loader, ir);
Lookup::DataProvider.register_types(loader)
add_object_type('Deferred', <<-PUPPET, loader)
{
attributes => {
# Fully qualified name of the function
name => { type => Pattern[/\\A[$]?[a-z][a-z0-9_]*(?:::[a-z][a-z0-9_]*)*\\z/] },
arguments => { type => Optional[Array[Any]], value => undef},
}
}
PUPPET
end
# Create and register a new `Object` type in the Puppet Type System and map it to an implementation class
#
# @param loader [Loader::Loader] The loader where the new type will be registered
# @param ir [ImplementationRegistry] The implementation registry that maps this class to the new type
# @param impl_class [Class] The class that is the implementation of the type
# @param type_name [String] The fully qualified name of the new type
# @param parent_name [String,nil] The fully qualified name of the parent type
# @param attributes_hash [Hash{String => Object}] A hash of attribute definitions for the new type
# @param functions_hash [Hash{String => Object}] A hash of function definitions for the new type
# @param equality [Array<String>] An array with names of attributes that participate in equality comparison
# @return [PObjectType] the created type. Not yet resolved
#
# @api private
def self.create_object_type(loader, ir, impl_class, type_name, parent_name, attributes_hash = EMPTY_HASH, functions_hash = EMPTY_HASH, equality = nil)
init_hash = {}
init_hash[Types::KEY_PARENT] = Types::PTypeReferenceType.new(parent_name) unless parent_name.nil?
init_hash[Types::KEY_ATTRIBUTES] = attributes_hash unless attributes_hash.empty?
init_hash[Types::KEY_FUNCTIONS] = functions_hash unless functions_hash.empty?
init_hash[Types::KEY_EQUALITY] = equality unless equality.nil?
ir.register_implementation(type_name, impl_class)
add_type(Types::PObjectType.new(type_name, init_hash), loader)
end
def self.add_object_type(name, body, loader)
add_type(Types::PObjectType.new(name, Parser::EvaluatingParser.new.parse_string(body).body), loader)
end
def self.add_alias(name, type, loader, name_authority = RUNTIME_NAME_AUTHORITY)
add_type(Types::PTypeAliasType.new(name, nil, type), loader, name_authority)
end
def self.add_type(type, loader, name_authority = RUNTIME_NAME_AUTHORITY)
loader.set_entry(Loader::TypedName.new(:type, type.name, name_authority), type)
type
end
def self.register_implementations(impls, name_authority = RUNTIME_NAME_AUTHORITY)
Loaders.loaders.register_implementations(impls, name_authority)
end
def self.register_aliases(aliases, name_authority = RUNTIME_NAME_AUTHORITY, loader = Loaders.loaders.private_environment_loader)
aliases.each do |name, type_string|
add_type(Types::PTypeAliasType.new(name, Types::TypeFactory.type_reference(type_string), nil), loader, name_authority)
end
aliases.each_key.map { |name| loader.load(:type, name).resolve(loader) }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/serialization.rb | lib/puppet/pops/serialization.rb | # frozen_string_literal: true
module Puppet::Pops
module Serialization
def self.not_implemented(impl, method_name)
raise NotImplementedError, "The class #{impl.class.name} should have implemented the method #{method_name}()"
end
class SerializationError < Puppet::Error
end
PCORE_TYPE_KEY = '__ptype'
# Key used when the value can be represented as, and recreated from, a single string that can
# be passed to a `from_string` method or an array of values that can be passed to the default
# initializer method.
PCORE_VALUE_KEY = '__pvalue'
# Type key used for hashes that contain keys that are not of type String
PCORE_TYPE_HASH = 'Hash'
# Type key used for symbols
PCORE_TYPE_SENSITIVE = 'Sensitive'
PCORE_TYPE_BINARY = 'Binary'
# Type key used for symbols
PCORE_TYPE_SYMBOL = 'Symbol'
# Type key used for Default
PCORE_TYPE_DEFAULT = 'Default'
# Type key used for document local references
PCORE_LOCAL_REF_SYMBOL = 'LocalRef'
end
end
require_relative 'serialization/json_path'
require_relative 'serialization/from_data_converter'
require_relative 'serialization/to_data_converter'
require_relative 'serialization/to_stringified_converter'
require_relative 'serialization/serializer'
require_relative 'serialization/deserializer'
require_relative 'serialization/json'
require_relative 'serialization/time_factory'
require_relative 'serialization/object'
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/adaptable.rb | lib/puppet/pops/adaptable.rb | # frozen_string_literal: true
# Adaptable is a mix-in module that adds adaptability to a class.
# This means that an adapter can
# associate itself with an instance of the class and store additional data/have behavior.
#
# This mechanism should be used when there is a desire to keep implementation concerns separate.
# In Ruby it is always possible to open and modify a class or instance to teach it new tricks, but it
# is however not possible to do this for two different versions of some service at the same time.
# The Adaptable pattern is also good when only a few of the objects of some class needs to have extra
# information (again possible in Ruby by adding instance variables dynamically). In fact, the implementation
# of Adaptable does just that; it adds an instance variable named after the adapter class and keeps an
# instance of this class in this slot.
#
# @note the implementation details; the fact that an instance variable is used to keep the adapter
# instance data should not
# be exploited as the implementation of _being adaptable_ may change in the future.
# @api private
#
module Puppet::Pops
module Adaptable
# Base class for an Adapter.
#
# A typical adapter just defines some accessors.
#
# A more advanced adapter may need to setup the adapter based on the object it is adapting.
# @example Making Duck adaptable
# class Duck
# include Puppet::Pops::Adaptable
# end
# @example Giving a Duck a nick name
# class NickNameAdapter < Puppet::Pops::Adaptable::Adapter
# attr_accessor :nick_name
# end
# d = Duck.new
# NickNameAdapter.adapt(d).nick_name = "Daffy"
# NickNameAdapter.get(d).nick_name # => "Daffy"
#
# @example Giving a Duck a more elaborate nick name
# class NickNameAdapter < Puppet::Pops::Adaptable::Adapter
# attr_accessor :nick_name, :object
# def initialize o
# @object = o
# @nick_name = "Yo"
# end
# def nick_name
# "#{@nick_name}, the #{o.class.name}"
# end
# def NickNameAdapter.create_adapter(o)
# x = new o
# x
# end
# end
# d = Duck.new
# n = NickNameAdapter.adapt(d)
# n.nick_name # => "Yo, the Duck"
# n.nick_name = "Daffy"
# n.nick_name # => "Daffy, the Duck"
# @example Using a block to set values
# NickNameAdapter.adapt(o) { |a| a.nick_name = "Buddy!" }
# NickNameAdapter.adapt(o) { |a, o| a.nick_name = "You're the best #{o.class.name} I met."}
#
class Adapter
# Returns an existing adapter for the given object, or nil, if the object is not
# adapted.
#
# @param o [Adaptable] object to get adapter from
# @return [Adapter<self>] an adapter of the same class as the receiver of #get
# @return [nil] if the given object o has not been adapted by the receiving adapter
# @raise [ArgumentError] if the object is not adaptable
#
def self.get(o)
attr_name = self_attr_name
o.instance_variable_get(attr_name)
end
# Returns an existing adapter for the given object, or creates a new adapter if the
# object has not been adapted, or the adapter has been cleared.
#
# @example Using a block to set values
# NickNameAdapter.adapt(o) { |a| a.nick_name = "Buddy!" }
# NickNameAdapter.adapt(o) { |a, o| a.nick_name = "Your the best #{o.class.name} I met."}
# @overload adapt(o)
# @overload adapt(o, {|adapter| block})
# @overload adapt(o, {|adapter, o| block})
# @param o [Adaptable] object to add adapter to
# @yieldparam adapter [Adapter<self>] the created adapter
# @yieldparam o [Adaptable] optional, the given adaptable
# @param block [Proc] optional, evaluated in the context of the adapter (existing or new)
# @return [Adapter<self>] an adapter of the same class as the receiver of the call
# @raise [ArgumentError] if the given object o is not adaptable
#
def self.adapt(o, &block)
attr_name = self_attr_name
value = o.instance_variable_get(attr_name)
adapter = value || associate_adapter(create_adapter(o), o)
if block_given?
if block.arity == 1
block.call(adapter)
else
block.call(adapter, o)
end
end
adapter
end
# Creates a new adapter, associates it with the given object and returns the adapter.
#
# @example Using a block to set values
# NickNameAdapter.adapt_new(o) { |a| a.nick_name = "Buddy!" }
# NickNameAdapter.adapt_new(o) { |a, o| a.nick_name = "Your the best #{o.class.name} I met."}
# This is used when a fresh adapter is wanted instead of possible returning an
# existing adapter as in the case of {Adapter.adapt}.
# @overload adapt_new(o)
# @overload adapt_new(o, {|adapter| block})
# @overload adapt_new(o, {|adapter, o| block})
# @yieldparam adapter [Adapter<self>] the created adapter
# @yieldparam o [Adaptable] optional, the given adaptable
# @param o [Adaptable] object to add adapter to
# @param block [Proc] optional, evaluated in the context of the new adapter
# @return [Adapter<self>] an adapter of the same class as the receiver of the call
# @raise [ArgumentError] if the given object o is not adaptable
#
def self.adapt_new(o, &block)
adapter = associate_adapter(create_adapter(o), o)
if block_given?
if block.arity == 1
block.call(adapter)
else
block.call(adapter, o)
end
end
adapter
end
# Clears the adapter set in the given object o. Returns any set adapter or nil.
# @param o [Adaptable] the object where the adapter should be cleared
# @return [Adapter] if an adapter was set
# @return [nil] if the adapter has not been set
#
def self.clear(o)
attr_name = self_attr_name
if o.instance_variable_defined?(attr_name)
o.send(:remove_instance_variable, attr_name)
else
nil
end
end
# This base version creates an instance of the class (i.e. an instance of the concrete subclass
# of Adapter). A Specialization may want to create an adapter instance specialized for the given target
# object.
# @param o [Adaptable] The object to adapt. This implementation ignores this variable, but a
# specialization may want to initialize itself differently depending on the object it is adapting.
# @return [Adapter<self>] instance of the subclass of Adapter receiving the call
#
def self.create_adapter(o)
new
end
# Associates the given adapter with the given target object
# @param adapter [Adapter] the adapter to associate with the given object _o_
# @param o [Adaptable] the object to adapt
# @return [adapter] the given adapter
#
def self.associate_adapter(adapter, o)
o.instance_variable_set(self_attr_name, adapter)
adapter
end
# Returns a suitable instance variable name given a class name.
# The returned string is the fully qualified name of a class with '::' replaced by '_' since
# '::' is not allowed in an instance variable name.
# @param name [String] the fully qualified name of a class
# @return [String] the name with all '::' replaced by '_'
# @api private
#
def self.instance_var_name(name)
name.split(DOUBLE_COLON).join(USCORE)
end
# Returns the name of the class, or the name of the type if the class represents an Object type
# @return [String] the name of the class or type
def self.type_name
name
end
# Returns a suitable instance variable name for the _name_ of this instance. The name is created by calling
# Adapter#instance_var_name and then cached.
# @return [String] the instance variable name for _name_
# @api private
# rubocop:disable Naming/MemoizedInstanceVariableName
def self.self_attr_name
@attr_name_sym ||= :"@#{instance_var_name(type_name)}"
end
# rubocop:enable Naming/MemoizedInstanceVariableName
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/puppet_stack.rb | lib/puppet/pops/puppet_stack.rb | # frozen_string_literal: true
require_relative '../../puppet/thread_local'
module Puppet
module Pops
# Utility class for keeping track of the "Puppet stack", ie the file
# and line numbers of Puppet Code that created the current context.
#
# To use this make a call with:
#
# ```rb
# Puppet::Pops::PuppetStack.stack(file, line, receiver, message, args)
# ```
#
# To get the stack call:
#
# ```rb
# Puppet::Pops::PuppetStack.stacktrace
# ```
#
# or
#
# ```rb
# Puppet::Pops::PuppetStack.top_of_stack
# ```
#
# To support testing, a given file that is an empty string, or nil
# as well as a nil line number are supported. Such stack frames
# will be represented with the text `unknown` and `0´ respectively.
module PuppetStack
@stack = Puppet::ThreadLocal.new { Array.new }
def self.stack(file, line, obj, message, args, &block)
file = 'unknown' if file.nil? || file == ''
line = 0 if line.nil?
result = nil
@stack.value.unshift([file, line])
begin
if block_given?
result = obj.send(message, *args, &block)
else
result = obj.send(message, *args)
end
ensure
@stack.value.shift()
end
result
end
def self.stacktrace
@stack.value.dup
end
# Returns an Array with the top of the puppet stack, or an empty
# Array if there was no such entry.
def self.top_of_stack
@stack.value.first || []
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/patterns.rb | lib/puppet/pops/patterns.rb | # frozen_string_literal: true
# The Patterns module contains common regular expression patters for the Puppet DSL language
module Puppet::Pops::Patterns
# NUMERIC matches hex, octal, decimal, and floating point and captures several parts
# 0 = entire matched number, leading and trailing whitespace and sign included
# 1 = sign, +, - or nothing
# 2 = entire numeric part
# 3 = hexadecimal number
# 4 = non hex integer portion, possibly with leading 0 (octal)
# 5 = floating point part, starts with ".", decimals and optional exponent
#
# Thus, a hex number has group 3 value, an octal value has group 4 (if it starts with 0), and no group 3
# and a floating point value has group 4 and group 5.
#
NUMERIC = /\A[[:blank:]]*([-+]?)[[:blank:]]*((0[xX][0-9A-Fa-f]+)|(0?\d+)((?:\.\d+)?(?:[eE]-?\d+)?))[[:blank:]]*\z/
# Special expression that tests if there is whitespace between sign and number. The expression is used
# to strip such whitespace when normal Float or Integer conversion fails.
WS_BETWEEN_SIGN_AND_NUMBER = /\A([+-])[[:blank:]]+(.*)\z/
# ILLEGAL_P3_1_HOSTNAME matches if a hostname contains illegal characters.
# This check does not prevent pathological names like 'a....b', '.....', "---". etc.
ILLEGAL_HOSTNAME_CHARS = /[^-\w.]/
# NAME matches a name the same way as the lexer.
NAME = /\A((::)?[a-z]\w*)(::[a-z]\w*)*\z/
# CLASSREF_EXT matches a class reference the same way as the lexer - i.e. the external source form
# where each part must start with a capital letter A-Z.
#
CLASSREF_EXT = /\A((::){0,1}[A-Z]\w*)+\z/
# Same as CLASSREF_EXT but cannot start with '::'
#
CLASSREF_EXT_DECL = /\A[A-Z]\w*(?:::[A-Z]\w*)*\z/
# CLASSREF matches a class reference the way it is represented internally in the
# model (i.e. in lower case).
#
CLASSREF = /\A((::){0,1}[a-z]\w*)+\z/
# Same as CLASSREF but cannot start with '::'
#
CLASSREF_DECL = /\A[a-z]\w*(?:::[a-z]\w*)*\z/
# DOLLAR_VAR matches a variable name including the initial $ character
DOLLAR_VAR = /\$(::)?(\w+::)*\w+/
# VAR_NAME matches the name part of a variable (The $ character is not included)
# Note, that only the final segment may start with an underscore.
# Note, regexp sensitive to backtracking
VAR_NAME = /\A(?:::)?(?:[a-z]\w*::)*[a-z_]\w*\z/
# PARAM_NAME matches the name part of a parameter (The $ character is not included)
PARAM_NAME = /\A[a-z_]\w*\z/
# A Numeric var name must be the decimal number 0, or a decimal number not starting with 0
NUMERIC_VAR_NAME = /\A(?:0|(?:[1-9][0-9]*))\z/
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/label_provider.rb | lib/puppet/pops/label_provider.rb | # frozen_string_literal: true
# Provides a label for an object.
# This simple implementation calls #to_s on the given object, and handles articles 'a/an/the'.
#
module Puppet::Pops::LabelProvider
VOWELS = %w[a e i o u y]
SKIPPED_CHARACTERS = %w[" ']
A = "a"
AN = "an"
# Provides a label for the given object by calling `to_s` on the object.
# The intent is for this method to be overridden in concrete label providers.
def label o
o.to_s
end
# Produces a label for the given text with indefinite article (a/an)
def a_an o
text = label(o)
"#{article(text)} #{text}"
end
# Produces a label for the given text with indefinite article (A/An)
def a_an_uc o
text = label(o)
"#{article(text).capitalize} #{text}"
end
# Produces a label for the given text with *definite article* (the).
def the o
"the #{label(o)}"
end
# Produces a label for the given text with *definite article* (The).
def the_uc o
"The #{label(o)}"
end
# Appends 's' to (optional) text if count != 1 else an empty string
def plural_s(count, text = '')
count == 1 ? text : "#{text}s"
end
# Combines several strings using commas and a final conjunction
def combine_strings(strings, conjunction = 'or')
case strings.size
when 0
''
when 1
strings[0]
when 2
"#{strings[0]} #{conjunction} #{strings[1]}"
else
"#{strings[0...-1].join(', ')}, #{conjunction} #{strings.last}"
end
end
# Produces an *indefinite article* (a/an) for the given text ('a' if
# it starts with a vowel) This is obviously flawed in the general
# sense as may labels have punctuation at the start and this method
# does not translate punctuation to English words. Also, if a vowel is
# pronounced as a consonant, the article should not be "an".
#
def article s
article_for_letter(first_letter_of(s))
end
private
def first_letter_of(string)
char = string[0, 1]
if SKIPPED_CHARACTERS.include? char
char = string[1, 1]
end
if char == ""
raise Puppet::DevError, _("<%{string}> does not appear to contain a word") % { string: string }
end
char
end
def article_for_letter(letter)
downcased = letter.downcase
if VOWELS.include? downcased
AN
else
A
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/utils.rb | lib/puppet/pops/utils.rb | # frozen_string_literal: true
# Provides utility methods
module Puppet::Pops
module Utils
# Can the given o be converted to numeric? (or is numeric already)
# Accepts a leading '::'
# Returns a boolean if the value is numeric
# If testing if value can be converted it is more efficient to call {#to_n} or {#to_n_with_radix} directly
# and check if value is nil.
def self.is_numeric?(o)
case o
when Numeric
true
else
!!Patterns::NUMERIC.match(relativize_name(o.to_s))
end
end
# Convert a match from Patterns::NUMERIC to floating point value if
# possible
def self.match_to_fp(match)
if match[5].to_s.length > 0
# Use default radix (default is decimal == 10) for floats
# Do not convert a value that is 0 raised to 10^somevalue to float - the value is always 0
# i.e. 0000.0e1, 0e1, 0.0000e1
if Integer(match[4]) == 0 && match[5] =~ /\A\.?0*[eE].*\z/
nil
else
fp_value = Float(match[2])
if fp_value != Float::INFINITY
match[1] == '-' ? -fp_value : fp_value
else
nil
end
end
end
end
# To Numeric with radix, or nil if not a number.
# If the value is already Numeric it is returned verbatim with a radix of 10.
# @param o [String, Number] a string containing a number in octal, hex, integer (decimal) or floating point form
# with optional sign +/-
# @return [Array<Number, Integer>, nil] array with converted number and radix, or nil if not possible to convert
# @api public
#
def self.to_n_with_radix o
case o
when String
match = Patterns::NUMERIC.match(relativize_name(o))
if !match
nil
elsif match[5].to_s.length > 0
fp_value = match_to_fp(match)
fp_value.nil? ? nil : [fp_value, 10]
else
# Set radix (default is decimal == 10)
radix = 10
if match[3].to_s.length > 0
radix = 16
elsif match[4].to_s.length > 1 && match[4][0, 1] == '0'
radix = 8
end
# Ruby 1.8.7 does not have a second argument to Kernel method that creates an
# integer from a string, it relies on the prefix 0x, 0X, 0 (and unsupported in puppet binary 'b')
# We have the correct string here, match[2] is safe to parse without passing on radix
match[1] == '-' ? [-Integer(match[2]), radix] : [Integer(match[2]), radix]
end
when Numeric
# Impossible to calculate radix, assume decimal
[o, 10]
else
nil
end
rescue ArgumentError
nil
end
# To Numeric (or already numeric)
# Returns nil if value is not numeric, else an Integer or Float. A String may have an optional sign.
#
# A leading '::' is accepted (and ignored)
#
def self.to_n o
case o
when String
match = Patterns::NUMERIC.match(relativize_name(o))
if !match
nil
elsif match[5].to_s.length > 0
match_to_fp(match)
else
match[1] == '-' ? -Integer(match[2]) : Integer(match[2])
end
when Numeric
o
else
nil
end
rescue ArgumentError
nil
end
# is the name absolute (i.e. starts with ::)
def self.is_absolute? name
name.start_with? "::"
end
def self.name_to_segments name
name.split("::")
end
def self.relativize_name name
is_absolute?(name) ? name[2..] : name
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/loaders.rb | lib/puppet/pops/loaders.rb | # frozen_string_literal: true
module Puppet::Pops
# This is the container for all Loader instances. Each Loader instance has a `loader_name` by which it can be uniquely
# identified within this container.
# A Loader can be private or public. In general, code will have access to the private loader associated with the
# location of the code. It will be parented by a loader that in turn have access to other public loaders that
# can load only such entries that have been publicly available. The split between public and private is not
# yet enforced in Puppet.
#
# The name of a private loader should always end with ' private'
#
class Loaders
class LoaderError < Puppet::Error; end
# Commented out the :static_loader and :puppet_system_loader
# because of rubocop offenses with duplicated definitions of
# these generated methods, but keeping them here for visibility
# on how the loaders are stacked.
# attr_reader :static_loader
# attr_reader :puppet_system_loader
attr_reader :puppet_cache_loader
attr_reader :public_environment_loader
attr_reader :private_environment_loader
attr_reader :environment
def self.new(environment, for_agent = false, load_from_pcore = true)
environment.lock.synchronize do
obj = environment.loaders
if obj.nil?
obj = allocate
obj.send(:initialize, environment, for_agent, load_from_pcore)
end
obj
end
end
def initialize(environment, for_agent, load_from_pcore = true)
# Protect against environment havoc
raise ArgumentError, _("Attempt to redefine already initialized loaders for environment") unless environment.loaders.nil?
environment.loaders = self
@environment = environment
@loaders_by_name = {}
add_loader_by_name(self.class.static_loader)
# Create the set of loaders
# 1. Puppet, loads from the "running" puppet - i.e. bundled functions, types, extension points and extensions
# These cannot be cached since a loaded instance will be bound to its closure scope which holds on to
# a compiler and all loaded types. Subsequent request would find remains of the environment that loaded
# the content. PUP-4461.
#
@puppet_system_loader = create_puppet_system_loader()
# 2. Cache loader(optional) - i.e. what puppet stores on disk via pluginsync; gate behind the for_agent flag.
# 3. Environment loader - i.e. what is bound across the environment, may change for each setup
# TODO: loaders need to work when also running in an agent doing catalog application. There is no
# concept of environment the same way as when running as a master (except when doing apply).
# The creation mechanisms should probably differ between the two.
@private_environment_loader =
if for_agent
@puppet_cache_loader = create_puppet_cache_loader
create_environment_loader(environment, @puppet_cache_loader, load_from_pcore)
else
create_environment_loader(environment, @puppet_system_loader, load_from_pcore)
end
Pcore.init_env(@private_environment_loader)
# 4. module loaders are set up from the create_environment_loader, they register themselves
end
# Called after loader has been added to Puppet Context as :loaders so that dynamic types can
# be pre-loaded with a fully configured loader system
def pre_load
@puppet_system_loader.load(:type, 'error')
end
# Clears the cached static and puppet_system loaders (to enable testing)
#
def self.clear
@@static_loader = nil
Puppet::Pops::Types::TypeFactory.clear
Model.class_variable_set(:@@pcore_ast_initialized, false)
Model.register_pcore_types
end
# Calls {#loaders} to obtain the {{Loaders}} instance and then uses it to find the appropriate loader
# for the given `module_name`, or for the environment in case `module_name` is `nil` or empty.
#
# @param module_name [String,nil] the name of the module
# @return [Loader::Loader] the found loader
# @raise [Puppet::ParseError] if no loader can be found
# @api private
def self.find_loader(module_name)
loaders.find_loader(module_name)
end
def self.static_implementation_registry
if !class_variable_defined?(:@@static_implementation_registry) || @@static_implementation_registry.nil?
ir = Types::ImplementationRegistry.new
Types::TypeParser.type_map.values.each { |t| ir.register_implementation(t.simple_name, t.class.name) }
@@static_implementation_registry = ir
end
@@static_implementation_registry
end
def self.static_loader
# The static loader can only be changed after a reboot
if !class_variable_defined?(:@@static_loader) || @@static_loader.nil?
@@static_loader = Loader::StaticLoader.new()
@@static_loader.register_aliases
Pcore.init(@@static_loader, static_implementation_registry)
end
@@static_loader
end
def self.implementation_registry
loaders = Puppet.lookup(:loaders) { nil }
loaders.nil? ? nil : loaders.implementation_registry
end
def register_implementations(obj_classes, name_authority)
self.class.register_implementations_with_loader(obj_classes, name_authority, @private_environment_loader)
end
# Register implementations using the global static loader
def self.register_static_implementations(obj_classes)
register_implementations_with_loader(obj_classes, Pcore::RUNTIME_NAME_AUTHORITY, static_loader)
end
def self.register_implementations_with_loader(obj_classes, name_authority, loader)
types = obj_classes.map do |obj_class|
type = obj_class._pcore_type
typed_name = Loader::TypedName.new(:type, type.name, name_authority)
entry = loader.loaded_entry(typed_name)
loader.set_entry(typed_name, type) if entry.nil? || entry.value.nil?
type
end
# Resolve lazy so that all types can cross reference each other
types.each { |type| type.resolve(loader) }
end
# Register the given type with the Runtime3TypeLoader. The registration will not happen unless
# the type system has been initialized.
#
# @param name [String,Symbol] the name of the entity being set
# @param origin [URI] the origin or the source where the type is defined
# @api private
def self.register_runtime3_type(name, origin)
loaders = Puppet.lookup(:loaders) { nil }
return nil if loaders.nil?
rt3_loader = loaders.runtime3_type_loader
return nil if rt3_loader.nil?
name = name.to_s
caps_name = Types::TypeFormatter.singleton.capitalize_segments(name)
typed_name = Loader::TypedName.new(:type, name)
rt3_loader.set_entry(typed_name, Types::PResourceType.new(caps_name), origin)
nil
end
# Finds a loader to use when deserializing a catalog and then subsequenlty use user
# defined types found in that catalog.
#
def self.catalog_loader
loaders = Puppet.lookup(:loaders) { nil }
if loaders.nil?
loaders = Loaders.new(Puppet.lookup(:current_environment), true)
Puppet.push_context(:loaders => loaders)
end
loaders.find_loader(nil)
end
# Finds the `Loaders` instance by looking up the :loaders in the global Puppet context
#
# @return [Loaders] the loaders instance
# @raise [Puppet::ParseError] if loader has been bound to the global context
# @api private
def self.loaders
loaders = Puppet.lookup(:loaders) { nil }
raise Puppet::ParseError, _("Internal Error: Puppet Context ':loaders' missing") if loaders.nil?
loaders
end
# Lookup a loader by its unique name.
#
# @param [String] loader_name the name of the loader to lookup
# @return [Loader] the found loader
# @raise [Puppet::ParserError] if no loader is found
def [](loader_name)
loader = @loaders_by_name[loader_name]
if loader.nil?
# Unable to find the module private loader. Try resolving the module
loader = private_loader_for_module(loader_name[0..-9]) if loader_name.end_with?(' private')
raise Puppet::ParseError, _("Unable to find loader named '%{loader_name}'") % { loader_name: loader_name } if loader.nil?
end
loader
end
# Finds the appropriate loader for the given `module_name`, or for the environment in case `module_name`
# is `nil` or empty.
#
# @param module_name [String,nil] the name of the module
# @return [Loader::Loader] the found loader
# @raise [Puppet::ParseError] if no loader can be found
# @api private
def find_loader(module_name)
if module_name.nil? || EMPTY_STRING == module_name
# Use the public environment loader
public_environment_loader
else
# TODO : Later check if definition is private, and then add it to private_loader_for_module
#
loader = public_loader_for_module(module_name)
if loader.nil?
raise Puppet::ParseError, _("Internal Error: did not find public loader for module: '%{module_name}'") % { module_name: module_name }
end
loader
end
end
def implementation_registry
# Environment specific implementation registry
@implementation_registry ||= Types::ImplementationRegistry.new(self.class.static_implementation_registry)
end
def static_loader
self.class.static_loader
end
def puppet_system_loader
@puppet_system_loader
end
def runtime3_type_loader
@runtime3_type_loader
end
def public_loader_for_module(module_name)
md = @module_resolver[module_name] || (return nil)
# Note, this loader is not resolved until there is interest in the visibility of entities from the
# perspective of something contained in the module. (Many request may pass through a module loader
# without it loading anything.
# See {#private_loader_for_module}, and not in {#configure_loaders_for_modules}
md.public_loader
end
def private_loader_for_module(module_name)
md = @module_resolver[module_name] || (return nil)
# Since there is interest in the visibility from the perspective of entities contained in the
# module, it must be resolved (to provide this visibility).
# See {#configure_loaders_for_modules}
unless md.resolved?
@module_resolver.resolve(md)
end
md.private_loader
end
def add_loader_by_name(loader)
name = loader.loader_name
if @loaders_by_name.include?(name)
raise Puppet::ParseError, _("Internal Error: Attempt to redefine loader named '%{name}'") % { name: name }
end
@loaders_by_name[name] = loader
end
# Load the main manifest for the given environment
#
# There are two sources that can be used for the initial parse:
#
# 1. The value of `Puppet[:code]`: Puppet can take a string from
# its settings and parse that as a manifest. This is used by various
# Puppet applications to read in a manifest and pass it to the
# environment as a side effect. This is attempted first.
# 2. The contents of the environment's +manifest+ attribute: Puppet will
# try to load the environment manifest. The manifest must be a file.
#
# @return [Model::Program] The manifest parsed into a model object
def load_main_manifest
parser = Parser::EvaluatingParser.singleton
parsed_code = Puppet[:code]
program = if parsed_code != ""
parser.parse_string(parsed_code, 'unknown-source-location')
else
file = @environment.manifest
# if the manifest file is a reference to a directory, parse and
# combine all .pp files in that directory
if file == Puppet::Node::Environment::NO_MANIFEST
nil
elsif File.directory?(file)
raise Puppet::Error, "manifest of environment '#{@environment.name}' appoints directory '#{file}'. It must be a file"
elsif File.exist?(file)
parser.parse_file(file)
else
raise Puppet::Error, "manifest of environment '#{@environment.name}' appoints '#{file}'. It does not exist"
end
end
instantiate_definitions(program, public_environment_loader) unless program.nil?
program
rescue Puppet::ParseErrorWithIssue => detail
detail.environment = @environment.name
raise
rescue => detail
msg = _('Could not parse for environment %{env}: %{detail}') % { env: @environment, detail: detail }
error = Puppet::Error.new(msg)
error.set_backtrace(detail.backtrace)
raise error
end
# Add 4.x definitions found in the given program to the given loader.
def instantiate_definitions(program, loader)
program.definitions.each { |d| instantiate_definition(d, loader) }
nil
end
# Add given 4.x definition to the given loader.
def instantiate_definition(definition, loader)
case definition
when Model::PlanDefinition
instantiate_PlanDefinition(definition, loader)
when Model::FunctionDefinition
instantiate_FunctionDefinition(definition, loader)
when Model::TypeAlias
instantiate_TypeAlias(definition, loader)
when Model::TypeMapping
instantiate_TypeMapping(definition, loader)
else
raise Puppet::ParseError, "Internal Error: Unknown type of definition - got '#{definition.class}'"
end
end
private
def instantiate_PlanDefinition(plan_definition, loader)
typed_name, f = Loader::PuppetPlanInstantiator.create_from_model(plan_definition, loader)
loader.set_entry(typed_name, f, plan_definition.locator.to_uri(plan_definition))
nil
end
def instantiate_FunctionDefinition(function_definition, loader)
# Instantiate Function, and store it in the loader
typed_name, f = Loader::PuppetFunctionInstantiator.create_from_model(function_definition, loader)
loader.set_entry(typed_name, f, function_definition.locator.to_uri(function_definition))
nil
end
def instantiate_TypeAlias(type_alias, loader)
# Bind the type alias to the loader using the alias
Puppet::Pops::Loader::TypeDefinitionInstantiator.create_from_model(type_alias, loader)
nil
end
def instantiate_TypeMapping(type_mapping, loader)
tf = Types::TypeParser.singleton
lhs = tf.interpret(type_mapping.type_expr, loader)
rhs = tf.interpret_any(type_mapping.mapping_expr, loader)
implementation_registry.register_type_mapping(lhs, rhs)
nil
end
def create_puppet_system_loader
Loader::ModuleLoaders.system_loader_from(static_loader, self)
end
def create_puppet_cache_loader
Loader::ModuleLoaders.cached_loader_from(puppet_system_loader, self)
end
def create_environment_loader(environment, parent_loader, load_from_pcore = true)
# This defines where to start parsing/evaluating - the "initial import" (to use 3x terminology)
# Is either a reference to a single .pp file, or a directory of manifests. If the environment becomes
# a module and can hold functions, types etc. then these are available across all other modules without
# them declaring this dependency - it is however valuable to be able to treat it the same way
# bindings and other such system related configuration.
# This is further complicated by the many options available:
# - The environment may not have a directory, the code comes from one appointed 'manifest' (site.pp)
# - The environment may have a directory and also point to a 'manifest'
# - The code to run may be set in settings (code)
# Further complication is that there is nothing specifying what the visibility is into
# available modules. (3x is everyone sees everything).
# Puppet binder currently reads confdir/bindings - that is bad, it should be using the new environment support.
# env_conf is setup from the environment_dir value passed into Puppet::Environments::Directories.new
env_conf = Puppet.lookup(:environments).get_conf(environment.name)
env_path = env_conf.nil? || !env_conf.is_a?(Puppet::Settings::EnvironmentConf) ? nil : env_conf.path_to_env
if Puppet[:tasks]
loader = Loader::ModuleLoaders.environment_loader_from(parent_loader, self, env_path)
else
# Create the 3.x resource type loader
static_loader.runtime_3_init
# Create pcore resource type loader, if applicable
pcore_resource_type_loader = if load_from_pcore && env_path
Loader::ModuleLoaders.pcore_resource_type_loader_from(parent_loader, self, env_path)
else
nil
end
@runtime3_type_loader = add_loader_by_name(Loader::Runtime3TypeLoader.new(parent_loader, self, environment, pcore_resource_type_loader))
if env_path.nil?
# Not a real directory environment, cannot work as a module TODO: Drop when legacy env are dropped?
loader = add_loader_by_name(Loader::SimpleEnvironmentLoader.new(@runtime3_type_loader, Loader::ENVIRONMENT, environment))
else
# View the environment as a module to allow loading from it - this module is always called 'environment'
loader = Loader::ModuleLoaders.environment_loader_from(@runtime3_type_loader, self, env_path)
end
end
# An environment has a module path even if it has a null loader
configure_loaders_for_modules(loader, environment)
# modules should see this loader
@public_environment_loader = loader
# Code in the environment gets to see all modules (since there is no metadata for the environment)
# but since this is not given to the module loaders, they can not load global code (since they can not
# have prior knowledge about this
loader = add_loader_by_name(Loader::DependencyLoader.new(loader, Loader::ENVIRONMENT_PRIVATE, @module_resolver.all_module_loaders(), environment))
# The module loader gets the private loader via a lazy operation to look up the module's private loader.
# This does not work for an environment since it is not resolved the same way.
# TODO: The EnvironmentLoader could be a specialized loader instead of using a ModuleLoader to do the work.
# This is subject to future design - an Environment may move more in the direction of a Module.
@public_environment_loader.private_loader = loader
loader
end
def configure_loaders_for_modules(parent_loader, environment)
@module_resolver = mr = ModuleResolver.new(self)
environment.modules.each do |puppet_module|
# Create data about this module
md = LoaderModuleData.new(puppet_module)
mr[puppet_module.name] = md
md.public_loader = Loader::ModuleLoaders.module_loader_from(parent_loader, self, md.name, md.path)
end
# NOTE: Do not resolve all modules here - this is wasteful if only a subset of modules / functions are used
# The resolution is triggered by asking for a module's private loader, since this means there is interest
# in the visibility from that perspective.
# If later, it is wanted that all resolutions should be made up-front (to capture errors eagerly, this
# can be introduced (better for production), but may be irritating in development mode.
end
# =LoaderModuleData
# Information about a Module and its loaders.
# TODO: should have reference to real model element containing all module data; this is faking it
# TODO: Should use Puppet::Module to get the metadata (as a hash) - a somewhat blunt instrument, but that is
# what is available with a reasonable API.
#
class LoaderModuleData
attr_accessor :public_loader
attr_accessor :private_loader
attr_accessor :resolutions
# The Puppet::Module this LoaderModuleData represents in the loader configuration
attr_reader :puppet_module
# @param puppet_module [Puppet::Module] the module instance for the module being represented
#
def initialize(puppet_module)
@puppet_module = puppet_module
@resolutions = []
@public_loader = nil
@private_loader = nil
end
def name
@puppet_module.name
end
def version
@puppet_module.version
end
def path
@puppet_module.path
end
def resolved?
!@private_loader.nil?
end
def restrict_to_dependencies?
@puppet_module.has_metadata?
end
def unmet_dependencies?
@puppet_module.unmet_dependencies.any?
end
def dependency_names
@puppet_module.dependencies_as_modules.collect(&:name)
end
end
# Resolves module loaders - resolution of model dependencies is done by Puppet::Module
#
class ModuleResolver
def initialize(loaders)
@loaders = loaders
@index = {}
@all_module_loaders = nil
end
def [](name)
@index[name]
end
def []=(name, module_data)
@index[name] = module_data
end
def all_module_loaders
@all_module_loaders ||= @index.values.map(&:public_loader)
end
def resolve(module_data)
if module_data.resolved?
nil
else
module_data.private_loader =
if module_data.restrict_to_dependencies?
create_loader_with_dependencies_first(module_data)
else
create_loader_with_all_modules_visible(module_data)
end
end
end
private
def create_loader_with_all_modules_visible(from_module_data)
@loaders.add_loader_by_name(Loader::DependencyLoader.new(from_module_data.public_loader, "#{from_module_data.name} private", all_module_loaders(), @loaders.environment))
end
def create_loader_with_dependencies_first(from_module_data)
dependency_loaders = from_module_data.dependency_names.collect { |name| @index[name].public_loader }
visible_loaders = dependency_loaders + (all_module_loaders() - dependency_loaders)
@loaders.add_loader_by_name(Loader::DependencyLoader.new(from_module_data.public_loader, "#{from_module_data.name} private", visible_loaders, @loaders.environment))
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/merge_strategy.rb | lib/puppet/pops/merge_strategy.rb | # frozen_string_literal: true
require 'deep_merge/core'
module Puppet::Pops
# Merges to objects into one based on an implemented strategy.
#
class MergeStrategy
NOT_FOUND = Object.new.freeze
def self.strategies
@@strategies ||= {}
end
private_class_method :strategies
# Finds the merge strategy for the given _merge_, creates an instance of it and returns that instance.
#
# @param merge [MergeStrategy,String,Hash<String,Object>,nil] The merge strategy. Can be a string or symbol denoting the key
# identifier or a hash with options where the key 'strategy' denotes the key
# @return [MergeStrategy] The matching merge strategy
#
def self.strategy(merge)
return DefaultMergeStrategy::INSTANCE unless merge
return merge if merge.is_a?(MergeStrategy)
if merge.is_a?(Hash)
merge_strategy = merge['strategy']
if merge_strategy.nil?
# TRANSLATORS 'merge' is a variable name and 'strategy' is a key and should not be translated
raise ArgumentError, _("The hash given as 'merge' must contain the name of a strategy in string form for the key 'strategy'")
end
merge_options = merge.size == 1 ? EMPTY_HASH : merge
else
merge_strategy = merge
merge_options = EMPTY_HASH
end
merge_strategy = merge_strategy.to_sym if merge_strategy.is_a?(String)
strategy_class = strategies[merge_strategy]
raise ArgumentError, _("Unknown merge strategy: '%{strategy}'") % { strategy: merge_strategy } if strategy_class.nil?
merge_options == EMPTY_HASH ? strategy_class::INSTANCE : strategy_class.new(merge_options)
end
# Returns the list of merge strategy keys known to this class
#
# @return [Array<Symbol>] List of strategy keys
#
def self.strategy_keys
strategies.keys - [:default, :unconstrained_deep, :reverse_deep]
end
# Adds a new merge strategy to the map of strategies known to this class
#
# @param strategy_class [Class<MergeStrategy>] The class of the added strategy
#
def self.add_strategy(strategy_class)
unless MergeStrategy > strategy_class
# TRANSLATORS 'MergeStrategies.add_strategy' is a method, 'stratgey_class' is a variable and 'MergeStrategy' is a class name and should not be translated
raise ArgumentError, _("MergeStrategies.add_strategy 'strategy_class' must be a 'MergeStrategy' class. Got %{strategy_class}") %
{ strategy_class: strategy_class }
end
strategies[strategy_class.key] = strategy_class
nil
end
# Finds a merge strategy that corresponds to the given _merge_ argument and delegates the task of merging the elements of _e1_ and _e2_ to it.
#
# @param e1 [Object] The first element
# @param e2 [Object] The second element
# @return [Object] The result of the merge
#
def self.merge(e1, e2, merge)
strategy(merge).merge(e1, e2)
end
def self.key
raise NotImplementedError, "Subclass must implement 'key'"
end
# Create a new instance of this strategy configured with the given _options_
# @param merge_options [Hash<String,Object>] Merge options
def initialize(options)
assert_type('The merge options', self.class.options_t, options) unless options.empty?
@options = options
end
# Merges the elements of _e1_ and _e2_ according to the rules of this strategy and options given when this
# instance was created
#
# @param e1 [Object] The first element
# @param e2 [Object] The second element
# @return [Object] The result of the merge
#
def merge(e1, e2)
checked_merge(
assert_type('The first element of the merge', value_t, e1),
assert_type('The second element of the merge', value_t, e2)
)
end
# TODO: API 5.0 Remove this method
# @deprecated
def merge_lookup(lookup_variants)
lookup(lookup_variants, Lookup::Invocation.current)
end
# Merges the result of yielding the given _lookup_variants_ to a given block.
#
# @param lookup_variants [Array] The variants to pass as second argument to the given block
# @return [Object] the merged value.
# @yield [} ]
# @yieldparam variant [Object] each variant given in the _lookup_variants_ array.
# @yieldreturn [Object] the value to merge with other values
# @throws :no_such_key if the lookup was unsuccessful
#
# Merges the result of yielding the given _lookup_variants_ to a given block.
#
# @param lookup_variants [Array] The variants to pass as second argument to the given block
# @return [Object] the merged value.
# @yield [} ]
# @yieldparam variant [Object] each variant given in the _lookup_variants_ array.
# @yieldreturn [Object] the value to merge with other values
# @throws :no_such_key if the lookup was unsuccessful
#
def lookup(lookup_variants, lookup_invocation)
case lookup_variants.size
when 0
throw :no_such_key
when 1
merge_single(yield(lookup_variants[0]))
else
lookup_invocation.with(:merge, self) do
result = lookup_variants.reduce(NOT_FOUND) do |memo, lookup_variant|
not_found = true
value = catch(:no_such_key) do
v = yield(lookup_variant)
not_found = false
v
end
if not_found
memo
else
memo.equal?(NOT_FOUND) ? convert_value(value) : merge(memo, value)
end
end
throw :no_such_key if result == NOT_FOUND
lookup_invocation.report_result(result)
end
end
end
# Converts a single value to the type expected when merging two elements
# @param value [Object] the value to convert
# @return [Object] the converted value
def convert_value(value)
value
end
# Applies the merge strategy on a single element. Only applicable for `unique`
# @param value [Object] the value to merge with nothing
# @return [Object] the merged value
def merge_single(value)
value
end
def options
@options
end
def configuration
if @options.nil? || @options.empty?
self.class.key.to_s
else
@options.include?('strategy') ? @options : { 'strategy' => self.class.key.to_s }.merge(@options)
end
end
protected
class << self
# Returns the type used to validate the options hash
#
# @return [Types::PStructType] the puppet type
#
def options_t
@options_t ||= Types::TypeParser.singleton.parse("Struct[{strategy=>Optional[Pattern[/#{key}/]]}]")
end
end
# Returns the type used to validate the options hash
#
# @return [Types::PAnyType] the puppet type
#
def value_t
raise NotImplementedError, "Subclass must implement 'value_t'"
end
def checked_merge(e1, e2)
raise NotImplementedError, "Subclass must implement 'checked_merge(e1,e2)'"
end
def assert_type(param, type, value)
Types::TypeAsserter.assert_instance_of(param, type, value)
end
end
# Simple strategy that returns the first value found. It never merges any values.
#
class FirstFoundStrategy < MergeStrategy
INSTANCE = new(EMPTY_HASH)
def self.key
:first
end
# Returns the first value found
#
# @param lookup_variants [Array] The variants to pass as second argument to the given block
# @return [Object] the merged value
# @throws :no_such_key unless the lookup was successful
#
def lookup(lookup_variants, _)
# First found does not continue when a root key was found and a subkey wasn't since that would
# simulate a hash merge
lookup_variants.each { |lookup_variant| catch(:no_such_key) { return yield(lookup_variant) } }
throw :no_such_key
end
protected
def value_t
@value_t ||= Types::PAnyType::DEFAULT
end
MergeStrategy.add_strategy(self)
end
# Same as {FirstFoundStrategy} but used when no strategy has been explicitly given
class DefaultMergeStrategy < FirstFoundStrategy
INSTANCE = new(EMPTY_HASH)
def self.key
:default
end
MergeStrategy.add_strategy(self)
end
# Produces a new hash by merging hash e1 with hash e2 in such a way that the values of duplicate keys
# will be those of e1
#
class HashMergeStrategy < MergeStrategy
INSTANCE = new(EMPTY_HASH)
def self.key
:hash
end
# @param e1 [Hash<String,Object>] The hash that will act as the source of the merge
# @param e2 [Hash<String,Object>] The hash that will act as the receiver for the merge
# @return [Hash<String,Object]] The merged hash
# @see Hash#merge
def checked_merge(e1, e2)
e2.merge(e1)
end
protected
def value_t
@value_t ||= Types::TypeParser.singleton.parse('Hash[String,Data]')
end
MergeStrategy.add_strategy(self)
end
# Merges two values that must be either scalar or arrays into a unique set of values.
#
# Scalar values will be converted into a one element arrays and array values will be flattened
# prior to forming the unique set. The order of the elements is preserved with e1 being the
# first contributor of elements and e2 the second.
#
class UniqueMergeStrategy < MergeStrategy
INSTANCE = new(EMPTY_HASH)
def self.key
:unique
end
# @param e1 [Array<Object>] The first array
# @param e2 [Array<Object>] The second array
# @return [Array<Object>] The unique set of elements
#
def checked_merge(e1, e2)
convert_value(e1) | convert_value(e2)
end
def convert_value(e)
e.is_a?(Array) ? e.flatten : [e]
end
# If _value_ is an array, then return the result of calling `uniq` on that array. Otherwise,
# the argument is returned.
# @param value [Object] the value to merge with nothing
# @return [Object] the merged value
def merge_single(value)
value.is_a?(Array) ? value.uniq : value
end
protected
def value_t
@value_t ||= Types::TypeParser.singleton.parse('Variant[Scalar,Array[Data]]')
end
MergeStrategy.add_strategy(self)
end
# Documentation copied from https://github.com/danielsdeleo/deep_merge/blob/master/lib/deep_merge/core.rb
# altered with respect to _preserve_unmergeables_ since this implementation always disables that option.
#
# The destination is dup'ed before the deep_merge is called to allow frozen objects as values.
#
# deep_merge method permits merging of arbitrary child elements. The two top level
# elements must be hashes. These hashes can contain unlimited (to stack limit) levels
# of child elements. These child elements to not have to be of the same types.
# Where child elements are of the same type, deep_merge will attempt to merge them together.
# Where child elements are not of the same type, deep_merge will skip or optionally overwrite
# the destination element with the contents of the source element at that level.
# So if you have two hashes like this:
# source = {:x => [1,2,3], :y => 2}
# dest = {:x => [4,5,'6'], :y => [7,8,9]}
# dest.deep_merge!(source)
# Results: {:x => [1,2,3,4,5,'6'], :y => 2}
#
# "deep_merge" will unconditionally overwrite any unmergeables and merge everything else.
#
# Options:
# Options are specified in the last parameter passed, which should be in hash format:
# hash.deep_merge!({:x => [1,2]}, {:knockout_prefix => '--'})
# - 'knockout_prefix' Set to string value to signify prefix which deletes elements from existing element. Defaults is _undef_
# - 'sort_merged_arrays' Set to _true_ to sort all arrays that are merged together. Default is _false_
# - 'merge_hash_arrays' Set to _true_ to merge hashes within arrays. Default is _false_
#
# Selected Options Details:
# :knockout_prefix => The purpose of this is to provide a way to remove elements
# from existing Hash by specifying them in a special way in incoming hash
# source = {:x => ['--1', '2']}
# dest = {:x => ['1', '3']}
# dest.ko_deep_merge!(source)
# Results: {:x => ['2','3']}
# Additionally, if the knockout_prefix is passed alone as a string, it will cause
# the entire element to be removed:
# source = {:x => '--'}
# dest = {:x => [1,2,3]}
# dest.ko_deep_merge!(source)
# Results: {:x => ""}
#
# :merge_hash_arrays => merge hashes within arrays
# source = {:x => [{:y => 1}]}
# dest = {:x => [{:z => 2}]}
# dest.deep_merge!(source, {:merge_hash_arrays => true})
# Results: {:x => [{:y => 1, :z => 2}]}
#
class DeepMergeStrategy < MergeStrategy
INSTANCE = new(EMPTY_HASH)
def self.key
:deep
end
def checked_merge(e1, e2)
dm_options = { :preserve_unmergeables => false }
options.each_pair { |k, v| dm_options[k.to_sym] = v unless k == 'strategy' }
# e2 (the destination) is deep cloned to avoid that the passed in object mutates
DeepMerge.deep_merge!(e1, deep_clone(e2), dm_options)
end
def deep_clone(value)
case value
when Hash
result = value.clone
value.each { |k, v| result[k] = deep_clone(v) }
result
when Array
value.map { |v| deep_clone(v) }
else
value
end
end
protected
class << self
# Returns a type that allows all deep_merge options except 'preserve_unmergeables' since we force
# the setting of that option to false
#
# @return [Types::PAnyType] the puppet type used when validating the options hash
def options_t
@options_t ||= Types::TypeParser.singleton.parse('Struct[{'\
"strategy=>Optional[Pattern[#{key}]],"\
'knockout_prefix=>Optional[String],'\
'merge_debug=>Optional[Boolean],'\
'merge_hash_arrays=>Optional[Boolean],'\
'sort_merged_arrays=>Optional[Boolean],'\
'}]')
end
end
def value_t
@value_t ||= Types::PAnyType::DEFAULT
end
MergeStrategy.add_strategy(self)
end
# Same as {DeepMergeStrategy} but without constraint on valid merge options
# (needed for backward compatibility with Hiera v3)
class UnconstrainedDeepMergeStrategy < DeepMergeStrategy
def self.key
:unconstrained_deep
end
# @return [Types::PAnyType] the puppet type used when validating the options hash
def self.options_t
@options_t ||= Types::TypeParser.singleton.parse('Hash[String[1],Any]')
end
MergeStrategy.add_strategy(self)
end
# Same as {UnconstrainedDeepMergeStrategy} but with reverse priority of merged elements.
# (needed for backward compatibility with Hiera v3)
class ReverseDeepMergeStrategy < UnconstrainedDeepMergeStrategy
INSTANCE = new(EMPTY_HASH)
def self.key
:reverse_deep
end
def checked_merge(e1, e2)
super(e2, e1)
end
MergeStrategy.add_strategy(self)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/semantic_error.rb | lib/puppet/pops/semantic_error.rb | # frozen_string_literal: true
# Error that is used to raise an Issue. See {Puppet::Pops::Issues}.
#
class Puppet::Pops::SemanticError < RuntimeError
attr_accessor :issue
attr_accessor :semantic
attr_accessor :options
# @param issue [Puppet::Pops::Issues::Issue] the issue describing the severity and message
# @param semantic [Puppet::Pops::Model::Locatable, nil] the expression causing the failure, or nil if unknown
# @param options [Hash] an options hash with Symbol to value mapping - these are the arguments to the issue
#
def initialize(issue, semantic = nil, options = {})
@issue = issue
@semantic = semantic
@options = options
end
def file
@options[:file]
end
def line
@options[:line]
end
def pos
@options[:pos]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/pn.rb | lib/puppet/pops/pn.rb | # frozen_string_literal: true
module Puppet::Pops
module PN
KEY_PATTERN = /^[A-Za-z_-][0-9A-Za-z_-]*$/
def pnError(message)
raise ArgumentError, message
end
def as_call(name)
Call.new(name, self)
end
def as_parameters
[self]
end
def ==(o)
eql?(o)
end
def to_s
s = ''.dup
format(nil, s)
s
end
def with_name(name)
Entry.new(name, self)
end
def double_quote(str, bld)
bld << '"'
str.each_codepoint do |codepoint|
case codepoint
when 0x09
bld << '\\t'
when 0x0a
bld << '\\n'
when 0x0d
bld << '\\r'
when 0x22
bld << '\\"'
when 0x5c
bld << '\\\\'
else
if codepoint < 0x20
bld << sprintf('\\o%3.3o', codepoint)
elsif codepoint <= 0x7f
bld << codepoint
else
bld << [codepoint].pack('U')
end
end
end
bld << '"'
end
def format_elements(elements, indent, b)
elements.each_with_index do |e, i|
if indent
b << "\n" << indent.current
elsif i > 0
b << ' '
end
e.format(indent, b)
end
end
class Indent
attr_reader :current
def initialize(indent = ' ', current = '')
@indent = indent
@current = current
end
def increase
Indent.new(@indent, @current + @indent)
end
end
class Call
include PN
attr_reader :name, :elements
def initialize(name, *elements)
@name = name
@elements = elements
end
def [](idx)
@elements[idx]
end
def as_call(name)
Call.new(name, *@elements)
end
def as_parameters
List.new(@elements)
end
def eql?(o)
o.is_a?(Call) && @name == o.name && @elements == o.elements
end
def format(indent, b)
b << '(' << @name
if @elements.size > 0
b << ' ' unless indent
format_elements(@elements, indent ? indent.increase : nil, b)
end
b << ')'
end
def to_data
{ '^' => [@name] + @elements.map(&:to_data) }
end
end
class Entry
attr_reader :key, :value
def initialize(key, value)
@key = key
@value = value
end
def eql?(o)
o.is_a?(Entry) && @key == o.key && @value == o.value
end
alias == eql?
end
class List
include PN
attr_reader :elements
def initialize(elements)
@elements = elements
end
def [](idx)
@elements[idx]
end
def as_call(name)
Call.new(name, *@elements)
end
def as_parameters
@elements
end
def eql?(o)
o.is_a?(List) && @elements == o.elements
end
def format(indent, b)
b << '['
format_elements(@elements, indent ? indent.increase : nil, b) unless @elements.empty?
b << ']'
end
def to_data
@elements.map(&:to_data)
end
end
class Literal
include PN
attr_reader :value
def initialize(value)
@value = value
end
def format(indent, b)
if @value.nil?
b << 'nil'
elsif value.is_a?(String)
double_quote(value, b)
else
b << value.to_s
end
end
def eql?(o)
o.is_a?(Literal) && @value == o.value
end
def to_data
@value
end
end
class Map
include PN
attr_reader :entries
def initialize(entries)
entries.each { |e| pnError("key #{e.key} does not conform to pattern /#{KEY_PATTERN.source}/)") unless e.key =~ KEY_PATTERN }
@entries = entries
end
def eql?(o)
o.is_a?(Map) && @entries == o.entries
end
def format(indent, b)
local_indent = indent ? indent.increase : nil
b << '{'
@entries.each_with_index do |e, i|
if indent
b << "\n" << local_indent.current
elsif i > 0
b << ' '
end
b << ':' << e.key
b << ' '
e.value.format(local_indent, b)
end
b << '}'
end
def to_data
r = []
@entries.each { |e| r << e.key << e.value.to_data }
{ '#' => r }
end
end
end
end
require_relative 'model/pn_transformer'
require_relative 'parser/pn_parser'
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/visitor.rb | lib/puppet/pops/visitor.rb | # frozen_string_literal: true
module Puppet::Pops
# A Visitor performs delegation to a given receiver based on the configuration of the Visitor.
# A new visitor is created with a given receiver, a method prefix, min, and max argument counts.
# e.g.
# visitor = Visitor.new(self, "visit_from", 1, 1)
# will make the visitor call "self.visit_from_CLASS(x)" where CLASS is resolved to the given
# objects class, or one of is ancestors, the first class for which there is an implementation of
# a method will be selected.
#
# Raises RuntimeError if there are too few or too many arguments, or if the receiver is not
# configured to handle a given visiting object.
#
class Visitor
attr_reader :receiver, :message, :min_args, :max_args, :cache
def initialize(receiver, message, min_args = 0, max_args = nil)
raise ArgumentError, "min_args must be >= 0" if min_args < 0
raise ArgumentError, "max_args must be >= min_args or nil" if max_args && max_args < min_args
@receiver = receiver
@message = message
@min_args = min_args
@max_args = max_args
@cache = Hash.new
end
# Visit the configured receiver
def visit(thing, *args)
visit_this(@receiver, thing, args)
end
NO_ARGS = EMPTY_ARRAY
# Visit an explicit receiver
def visit_this(receiver, thing, args)
raise "Visitor Error: Too few arguments passed. min = #{@min_args}" unless args.length >= @min_args
if @max_args
raise "Visitor Error: Too many arguments passed. max = #{@max_args}" unless args.length <= @max_args
end
method_name = @cache[thing.class]
if method_name
return receiver.send(method_name, thing, *args)
else
thing.class.ancestors().each do |ancestor|
name = ancestor.name
next if name.nil?
method_name = :"#{@message}_#{name.split(DOUBLE_COLON).last}"
next unless receiver.respond_to?(method_name, true)
@cache[thing.class] = method_name
return receiver.send(method_name, thing, *args)
end
end
raise "Visitor Error: the configured receiver (#{receiver.class}) can't handle instance of: #{thing.class}"
end
# Visit an explicit receiver
def visit_this_class(receiver, clazz, args)
raise "Visitor Error: Too few arguments passed. min = #{@min_args}" unless args.length >= @min_args
if @max_args
raise "Visitor Error: Too many arguments passed. max = #{@max_args}" unless args.length <= @max_args
end
method_name = @cache[clazz]
if method_name
return receiver.send(method_name, clazz, *args)
else
clazz.ancestors().each do |ancestor|
name = ancestor.name
next if name.nil?
method_name = :"#{@message}_#{name.split(DOUBLE_COLON).last}"
next unless receiver.respond_to?(method_name, true)
@cache[clazz] = method_name
return receiver.send(method_name, clazz, *args)
end
end
raise "Visitor Error: the configured receiver (#{receiver.class}) can't handle instance of: #{clazz}"
end
# Visit an explicit receiver with 0 args
# (This is ~30% faster than calling the general method)
#
def visit_this_0(receiver, thing)
method_name = @cache[thing.class]
if method_name
return receiver.send(method_name, thing)
end
visit_this(receiver, thing, NO_ARGS)
end
# Visit an explicit receiver with 1 args
# (This is ~30% faster than calling the general method)
#
def visit_this_1(receiver, thing, arg)
method_name = @cache[thing.class]
if method_name
return receiver.send(method_name, thing, arg)
end
visit_this(receiver, thing, [arg])
end
# Visit an explicit receiver with 2 args
# (This is ~30% faster than calling the general method)
#
def visit_this_2(receiver, thing, arg1, arg2)
method_name = @cache[thing.class]
if method_name
return receiver.send(method_name, thing, arg1, arg2)
end
visit_this(receiver, thing, [arg1, arg2])
end
# Visit an explicit receiver with 3 args
# (This is ~30% faster than calling the general method)
#
def visit_this_3(receiver, thing, arg1, arg2, arg3)
method_name = @cache[thing.class]
if method_name
return receiver.send(method_name, thing, arg1, arg2, arg3)
end
visit_this(receiver, thing, [arg1, arg2, arg3])
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/validation.rb | lib/puppet/pops/validation.rb | # frozen_string_literal: true
module Puppet::Pops
# A module with base functionality for validation of a model.
#
# * **Factory** - an abstract factory implementation that makes it easier to create a new validation factory.
# * **SeverityProducer** - produces a severity (:error, :warning, :ignore) for a given Issue
# * **DiagnosticProducer** - produces a Diagnostic which binds an Issue to an occurrence of that issue
# * **Acceptor** - the receiver/sink/collector of computed diagnostics
# * **DiagnosticFormatter** - produces human readable output for a Diagnostic
#
module Validation
# This class is an abstract base implementation of a _model validation factory_ that creates a validator instance
# and associates it with a fully configured DiagnosticProducer.
#
# A _validator_ is responsible for validating a model. There may be different versions of validation available
# for one and the same model; e.g. different semantics for different puppet versions, or different types of
# validation configuration depending on the context/type of validation that should be performed (static, vs. runtime, etc.).
#
# This class is abstract and must be subclassed. The subclass must implement the methods
# {#label_provider} and {#checker}. It is also expected that the subclass will override
# the severity_producer and configure the issues that should be reported as errors (i.e. if they should be ignored, produce
# a warning, or a deprecation warning).
#
# @abstract Subclass must implement {#checker}, and {#label_provider}
# @api public
#
class Factory
# Produces a validator with the given acceptor as the recipient of produced diagnostics.
# The acceptor is where detected issues are received (and typically collected).
#
# @param acceptor [Acceptor] the acceptor is the receiver of all detected issues
# @return [#validate] a validator responding to `validate(model)`
#
# @api public
#
def validator(acceptor)
checker(diagnostic_producer(acceptor))
end
# Produces the diagnostics producer to use given an acceptor of issues.
#
# @param acceptor [Acceptor] the acceptor is the receiver of all detected issues
# @return [DiagnosticProducer] a detector of issues
#
# @api public
#
def diagnostic_producer(acceptor)
DiagnosticProducer.new(acceptor, severity_producer(), label_provider())
end
# Produces the SeverityProducer to use
# Subclasses should implement and add specific overrides
#
# @return [SeverityProducer] a severity producer producing error, warning or ignore per issue
#
# @api public
#
def severity_producer
SeverityProducer.new
end
# Produces the checker to use.
#
# @abstract
#
# @api public
#
def checker(diagnostic_producer)
raise NoMethodError, "checker"
end
# Produces the label provider to use.
#
# @abstract
#
# @api public
#
def label_provider
raise NoMethodError, "label_provider"
end
end
# Decides on the severity of a given issue.
# The produced severity is one of `:error`, `:warning`, or `:ignore`.
# By default, a severity of `:error` is produced for all issues. To configure the severity
# of an issue call `#severity=(issue, level)`.
#
# @return [Symbol] a symbol representing the severity `:error`, `:warning`, or `:ignore`
#
# @api public
#
class SeverityProducer
SEVERITIES = { ignore: true, warning: true, error: true, deprecation: true }.freeze
# Creates a new instance where all issues are diagnosed as :error unless overridden.
# @param [Symbol] specifies default severity if :error is not wanted as the default
# @api public
#
def initialize(default_severity = :error)
# If diagnose is not set, the default is returned by the block
@severities = Hash.new default_severity
end
# Returns the severity of the given issue.
# @return [Symbol] severity level :error, :warning, or :ignore
# @api public
#
def severity(issue)
assert_issue(issue)
@severities[issue]
end
# @see {#severity}
# @api public
#
def [] issue
severity issue
end
# Override a default severity with the given severity level.
#
# @param issue [Issues::Issue] the issue for which to set severity
# @param level [Symbol] the severity level (:error, :warning, or :ignore).
# @api public
#
def []=(issue, level)
unless issue.is_a? Issues::Issue
raise Puppet::DevError, _("Attempt to set validation severity for something that is not an Issue. (Got %{issue})") % { issue: issue.class }
end
unless SEVERITIES[level]
raise Puppet::DevError, _("Illegal severity level: %{level} for '%{issue_code}'") % { issue_code: issue.issue_code, level: level }
end
unless issue.demotable? || level == :error
raise Puppet::DevError, _("Attempt to demote the hard issue '%{issue_code}' to %{level}") % { issue_code: issue.issue_code, level: level }
end
@severities[issue] = level
end
# Returns `true` if the issue should be reported or not.
# @return [Boolean] this implementation returns true for errors and warnings
#
# @api public
#
def should_report? issue
diagnose = @severities[issue]
diagnose == :error || diagnose == :warning || diagnose == :deprecation
end
# Checks if the given issue is valid.
# @api private
#
def assert_issue issue
unless issue.is_a? Issues::Issue
raise Puppet::DevError, _("Attempt to get validation severity for something that is not an Issue. (Got %{issue})") % { issue: issue.class }
end
end
end
# A producer of diagnostics.
# An producer of diagnostics is given each issue occurrence as they are found by a diagnostician/validator. It then produces
# a Diagnostic, which it passes on to a configured Acceptor.
#
# This class exists to aid a diagnostician/validator which will typically first check if a particular issue
# will be accepted at all (before checking for an occurrence of the issue; i.e. to perform check avoidance for expensive checks).
# A validator passes an instance of Issue, the semantic object (the "culprit"), a hash with arguments, and an optional
# exception. The semantic object is used to determine the location of the occurrence of the issue (file/line), and it
# sets keys in the given argument hash that may be used in the formatting of the issue message.
#
class DiagnosticProducer
# A producer of severity for a given issue
# @return [SeverityProducer]
#
attr_reader :severity_producer
# A producer of labels for objects involved in the issue
# @return [LabelProvider]
#
attr_reader :label_provider
# Initializes this producer.
#
# @param acceptor [Acceptor] a sink/collector of diagnostic results
# @param severity_producer [SeverityProducer] the severity producer to use to determine severity of a given issue
# @param label_provider [LabelProvider] a provider of model element type to human readable label
#
def initialize(acceptor, severity_producer, label_provider)
@acceptor = acceptor
@severity_producer = severity_producer
@label_provider = label_provider
end
def accept(issue, semantic, arguments = {}, except = nil)
return unless will_accept? issue
# Set label provider unless caller provided a special label provider
arguments[:label] ||= @label_provider
arguments[:semantic] ||= semantic
# A detail message is always provided, but is blank by default.
# TODO: this support is questionable, it requires knowledge that :detail is special
arguments[:detail] ||= ''
# Accept an Error as semantic if it supports methods #file(), #line(), and #pos()
if semantic.is_a?(StandardError)
unless semantic.respond_to?(:file) && semantic.respond_to?(:line) && semantic.respond_to?(:pos)
raise Puppet::DevError, _("Issue %{issue_code}: Cannot pass a %{class_name} as a semantic object when it does not support #pos(), #file() and #line()") %
{ issue_code: issue.issue_code, class_name: semantic.class }
end
end
source_pos = semantic
file = semantic.file unless semantic.nil?
severity = @severity_producer.severity(issue)
@acceptor.accept(Diagnostic.new(severity, issue, file, source_pos, arguments, except))
end
def will_accept? issue
@severity_producer.should_report? issue
end
end
class Diagnostic
attr_reader :severity
attr_reader :issue
attr_reader :arguments
attr_reader :exception
attr_reader :file
attr_reader :source_pos
def initialize severity, issue, file, source_pos, arguments = {}, exception = nil
@severity = severity
@issue = issue
@file = file
@source_pos = source_pos
@arguments = arguments
# TODO: Currently unused, the intention is to provide more information (stack backtrace, etc.) when
# debugging or similar - this to catch internal problems reported as higher level issues.
@exception = exception
end
# Two diagnostics are considered equal if the have the same issue, location and severity
# (arguments and exception are ignored)
# rubocop:disable Layout
def ==(o)
self.class == o.class &&
same_position?(o) &&
issue.issue_code == o.issue.issue_code &&
file == o.file &&
severity == o.severity
end
alias eql? ==
# rubocop:enable Layout
def hash
@hash ||= [file, source_pos.offset, issue.issue_code, severity].hash
end
# Position is equal if the diagnostic is not located or if referring to the same offset
def same_position?(o)
source_pos.nil? && o.source_pos.nil? || source_pos.offset == o.source_pos.offset
end
private :same_position?
end
# Formats a diagnostic for output.
# Produces a diagnostic output typical for a compiler (suitable for interpretation by tools)
# The format is:
# `file:line:pos: Message`, where pos, line and file are included if available.
#
class DiagnosticFormatter
def format diagnostic
"#{format_location(diagnostic)} #{format_severity(diagnostic)}#{format_message(diagnostic)}"
end
def format_message diagnostic
diagnostic.issue.format(diagnostic.arguments)
end
# This produces "Deprecation notice: " prefix if the diagnostic has :deprecation severity, otherwise "".
# The idea is that all other diagnostics are emitted with the methods Puppet.err (or an exception), and
# Puppet.warning.
# @note Note that it is not a good idea to use Puppet.deprecation_warning as it is for internal deprecation.
#
def format_severity diagnostic
diagnostic.severity == :deprecation ? "Deprecation notice: " : ""
end
def format_location diagnostic
file = diagnostic.file
file = (file.is_a?(String) && file.empty?) ? nil : file
line = pos = nil
if diagnostic.source_pos
line = diagnostic.source_pos.line
pos = diagnostic.source_pos.pos
end
if file && line && pos
"#{file}:#{line}:#{pos}:"
elsif file && line
"#{file}:#{line}:"
elsif file
"#{file}:"
else
""
end
end
end
# Produces a diagnostic output in the "puppet style", where the location is appended with an "at ..." if the
# location is known.
#
class DiagnosticFormatterPuppetStyle < DiagnosticFormatter
def format diagnostic
if (location = format_location diagnostic) != ""
"#{format_severity(diagnostic)}#{format_message(diagnostic)}#{location}"
else
format_message(diagnostic)
end
end
# The somewhat (machine) unusable format in current use by puppet.
# have to be used here for backwards compatibility.
def format_location diagnostic
file = diagnostic.file
file = (file.is_a?(String) && file.empty?) ? nil : file
line = pos = nil
if diagnostic.source_pos
line = diagnostic.source_pos.line
pos = diagnostic.source_pos.pos
end
if file && line && pos
" at #{file}:#{line}:#{pos}"
elsif file && line
" at #{file}:#{line}"
elsif line && pos
" at line #{line}:#{pos}"
elsif line
" at line #{line}"
elsif file
" in #{file}"
else
""
end
end
end
# An acceptor of diagnostics.
# An acceptor of diagnostics is given each issue as they are found by a diagnostician/validator. An
# acceptor can collect all found issues, or decide to collect a few and then report, or give up as the first issue
# if found.
# This default implementation collects all diagnostics in the order they are produced, and can then
# answer questions about what was diagnosed.
#
class Acceptor
# All diagnostic in the order they were issued
attr_reader :diagnostics
# The number of :warning severity issues + number of :deprecation severity issues
attr_reader :warning_count
# The number of :error severity issues
attr_reader :error_count
# Initializes this diagnostics acceptor.
# By default, the acceptor is configured with a default severity producer.
# @param severity_producer [SeverityProducer] the severity producer to use to determine severity of an issue
#
# TODO add semantic_label_provider
#
def initialize
@diagnostics = []
@error_count = 0
@warning_count = 0
end
# Returns true when errors have been diagnosed.
def errors?
@error_count > 0
end
# Returns true when warnings have been diagnosed.
def warnings?
@warning_count > 0
end
# Returns true when errors and/or warnings have been diagnosed.
def errors_or_warnings?
errors? || warnings?
end
# Returns the diagnosed errors in the order they were reported.
def errors
@diagnostics.select { |d| d.severity == :error }
end
# Returns the diagnosed warnings in the order they were reported.
# (This includes :warning and :deprecation severity)
def warnings
@diagnostics.select { |d| d.severity == :warning || d.severity == :deprecation }
end
def errors_and_warnings
@diagnostics.select { |d| d.severity != :ignore }
end
# Returns the ignored diagnostics in the order they were reported (if reported at all)
def ignored
@diagnostics.select { |d| d.severity == :ignore }
end
# Add a diagnostic, or all diagnostics from another acceptor to the set of diagnostics
# @param diagnostic [Diagnostic, Acceptor] diagnostic(s) that should be accepted
def accept(diagnostic)
if diagnostic.is_a?(Acceptor)
diagnostic.diagnostics.each { |d| _accept(d) }
else
_accept(diagnostic)
end
end
# Prunes the contain diagnostics by removing those for which the given block returns true.
# The internal statistics is updated as a consequence of removing.
# @return [Array<Diagnostic, nil] the removed set of diagnostics or nil if nothing was removed
#
def prune(&block)
removed = []
@diagnostics.delete_if do |d|
should_remove = yield(d)
if should_remove
removed << d
end
should_remove
end
removed.each do |d|
case d.severity
when :error
@error_count -= 1
when :warning
@warning_count -= 1
# there is not ignore_count
end
end
removed.empty? ? nil : removed
end
private
def _accept(diagnostic)
@diagnostics << diagnostic
case diagnostic.severity
when :error
@error_count += 1
when :deprecation, :warning
@warning_count += 1
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/adapters.rb | lib/puppet/pops/adapters.rb | # frozen_string_literal: true
# The Adapters module contains adapters for Documentation, Origin, SourcePosition, and Loader.
#
module Puppet::Pops
module Adapters
class ObjectIdCacheAdapter < Puppet::Pops::Adaptable::Adapter
attr_accessor :cache
def initialize
@cache = {}
end
# Retrieves a mutable hash with all stored values
def retrieve(o)
@cache[o.__id__] ||= {}
end
end
# A documentation adapter adapts an object with a documentation string.
# (The intended use is for a source text parser to extract documentation and store this
# in DocumentationAdapter instances).
#
class DocumentationAdapter < Adaptable::Adapter
# @return [String] The documentation associated with an object
attr_accessor :documentation
end
# An empty alternative adapter is used when there is the need to
# attach a value to be used if the original is empty. This is used
# when a lazy evaluation takes place, and the decision how to handle an
# empty case must be delayed.
#
class EmptyAlternativeAdapter < Adaptable::Adapter
# @return [Object] The alternative value associated with an object
attr_accessor :empty_alternative
end
# This class is for backward compatibility only. It's not really an adapter but it is
# needed for the puppetlabs-strings gem
# @deprecated
class SourcePosAdapter
def self.adapt(object)
new(object)
end
def initialize(object)
@object = object
end
def file
@object.file
end
def line
@object.line
end
def pos
@object.pos
end
def extract_text
@object.locator.extract_text(@object.offset, @object.length)
end
end
# A LoaderAdapter adapts an object with a {Loader}. This is used to make further loading from the
# perspective of the adapted object take place in the perspective of this Loader.
#
# It is typically enough to adapt the root of a model as a search is made towards the root of the model
# until a loader is found, but there is no harm in duplicating this information provided a contained
# object is adapted with the correct loader.
#
# @see Utils#find_adapter
# @api private
class LoaderAdapter < Adaptable::Adapter
attr_accessor :loader_name
# Finds the loader to use when loading originates from the source position of the given argument.
#
# @param instance [Model::PopsObject] The model object
# @param file [String] the file from where the model was parsed
# @param default_loader [Loader] the loader to return if no loader is found for the model
# @return [Loader] the found loader or default_loader if it could not be found
#
def self.loader_for_model_object(model, file = nil, default_loader = nil)
loaders = Puppet.lookup(:loaders) { nil }
if loaders.nil?
default_loader || Loaders.static_loader
else
loader_name = loader_name_by_source(loaders.environment, model, file)
if loader_name.nil?
default_loader || loaders[Loader::ENVIRONMENT_PRIVATE]
else
loaders[loader_name]
end
end
end
class PathsAndNameCacheAdapter < Puppet::Pops::Adaptable::Adapter
attr_accessor :cache, :paths
def self.create_adapter(env)
adapter = super(env)
adapter.paths = env.modulepath.map { |p| Pathname.new(p) }
adapter.cache = {}
adapter
end
end
# Attempts to find the module that `instance` originates from by looking at it's {SourcePosAdapter} and
# compare the `locator.file` found there with the module paths given in the environment found in the
# given `scope`. If the file is found to be relative to a path, then the first segment of the relative
# path is interpreted as the name of a module. The object that the {SourcePosAdapter} is adapted to
# will then be adapted to the private loader for that module and that adapter is returned.
#
# The method returns `nil` when no module could be found.
#
# @param environment [Puppet::Node::Environment] the current environment
# @param instance [Model::PopsObject] the AST for the code
# @param file [String] the path to the file for the code or `nil`
# @return [String] the name of the loader associated with the source
# @api private
def self.loader_name_by_source(environment, instance, file)
file = instance.file if file.nil?
return nil if file.nil? || EMPTY_STRING == file
pn_adapter = PathsAndNameCacheAdapter.adapt(environment)
dir = File.dirname(file)
pn_adapter.cache.fetch(dir) do |key|
mod = find_module_for_dir(environment, pn_adapter.paths, dir)
loader_name = mod.nil? ? nil : "#{mod.name} private"
pn_adapter.cache[key] = loader_name
end
end
# @api private
def self.find_module_for_dir(environment, paths, dir)
return nil if dir.nil?
file_path = Pathname.new(dir)
paths.each do |path|
begin
relative_path = file_path.relative_path_from(path).to_s.split(File::SEPARATOR)
rescue ArgumentError
# file_path was not relative to the module_path. That's OK.
next
end
if relative_path.length > 1
mod = environment.module(relative_path[0])
return mod unless mod.nil?
end
end
nil
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/lookup.rb | lib/puppet/pops/lookup.rb | # frozen_string_literal: true
# This class is the backing implementation of the Puppet function 'lookup'.
# See puppet/functions/lookup.rb for documentation.
#
module Puppet::Pops
module Lookup
LOOKUP_OPTIONS = 'lookup_options'
GLOBAL = '__global__'
# Performs a lookup in the configured scopes and optionally merges the default.
#
# This is a backing function and all parameters are assumed to have been type checked.
# See puppet/functions/lookup.rb for full documentation and all parameter combinations.
#
# @param name [String|Array<String>] The name or names to lookup
# @param type [Types::PAnyType|nil] The expected type of the found value
# @param default_value [Object] The value to use as default when no value is found
# @param has_default [Boolean] Set to _true_ if _default_value_ is included (_nil_ is a valid _default_value_)
# @param merge [MergeStrategy,String,Hash<String,Object>,nil] Merge strategy or hash with strategy and options
# @param lookup_invocation [Invocation] Invocation data containing scope, overrides, and defaults
# @return [Object] The found value
#
def self.lookup(name, value_type, default_value, has_default, merge, lookup_invocation)
names = name.is_a?(Array) ? name : [name]
# find first name that yields a non-nil result and wrap it in a two element array
# with name and value.
not_found = MergeStrategy::NOT_FOUND
override_values = lookup_invocation.override_values
result_with_name = [nil, not_found]
names.each do |key|
value = override_values.include?(key) ? assert_type(["Value found for key '%s' in override hash", key], value_type, override_values[key]) : not_found
catch(:no_such_key) { value = search_and_merge(key, lookup_invocation, merge, false) } if value.equal?(not_found)
next if value.equal?(not_found)
result_with_name = [key, assert_type('Found value', value_type, value)]
break
end
# Use the 'default_values' hash as a last resort if nothing is found
if result_with_name[1].equal?(not_found)
default_values = lookup_invocation.default_values
unless default_values.empty?
names.each do |key|
value = default_values.include?(key) ? assert_type(["Value found for key '%s' in default values hash", key], value_type, default_values[key]) : not_found
next if value.equal?(not_found)
result_with_name = [key, value]
break
end
end
end
answer = result_with_name[1]
if answer.equal?(not_found)
if block_given?
answer = assert_type('Value returned from default block', value_type, yield(name))
elsif has_default
answer = assert_type('Default value', value_type, default_value)
else
lookup_invocation.emit_debug_info(debug_preamble(names)) if Puppet[:debug]
fail_lookup(names)
end
end
lookup_invocation.emit_debug_info(debug_preamble(names)) if Puppet[:debug]
answer
end
# @api private
def self.debug_preamble(names)
if names.size == 1
names = "'#{names[0]}'"
else
names = names.map { |n| "'#{n}'" }.join(', ')
end
"Lookup of #{names}"
end
# @api private
def self.search_and_merge(name, lookup_invocation, merge, apl = true)
answer = lookup_invocation.lookup_adapter.lookup(name, lookup_invocation, merge)
lookup_invocation.emit_debug_info("Automatic Parameter Lookup of '#{name}'") if apl && Puppet[:debug]
answer
end
def self.assert_type(subject, type, value)
type ? Types::TypeAsserter.assert_instance_of(subject, type, value) : value
end
private_class_method :assert_type
def self.fail_lookup(names)
raise Puppet::DataBinding::LookupError,
n_("Function lookup() did not find a value for the name '%{name}'",
"Function lookup() did not find a value for any of the names [%{name_list}]", names.size) % { name: names[0], name_list: names.map { |n| "'#{n}'" }.join(', ') }
end
private_class_method :fail_lookup
end
end
require_relative 'lookup/lookup_adapter'
require_relative 'lookup/key_recorder'
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/issue_reporter.rb | lib/puppet/pops/issue_reporter.rb | # frozen_string_literal: true
module Puppet::Pops
class IssueReporter
# @param acceptor [Validation::Acceptor] the acceptor containing reported issues
# @option options [String] :message (nil) A message text to use as prefix in
# a single Error message
# @option options [Boolean] :emit_warnings (false) whether warnings should be emitted
# @option options [Boolean] :emit_errors (true) whether errors should be
# emitted or only the given message
# @option options [Exception] :exception_class (Puppet::ParseError) The exception to raise
#
def self.assert_and_report(acceptor, options)
return unless acceptor
max_errors = options[:max_errors] || Puppet[:max_errors]
max_warnings = options[:max_warnings] || Puppet[:max_warnings]
max_deprecations = options[:max_deprecations] || (Puppet[:disable_warnings].include?('deprecations') ? 0 : Puppet[:max_deprecations])
emit_warnings = options[:emit_warnings] || false
emit_errors = options[:emit_errors].nil? ? true : !!options[:emit_errors]
emit_message = options[:message]
emit_exception = options[:exception_class] || Puppet::ParseErrorWithIssue
# If there are warnings output them
warnings = acceptor.warnings
if emit_warnings && warnings.size > 0
formatter = Validation::DiagnosticFormatterPuppetStyle.new
emitted_w = 0
emitted_dw = 0
acceptor.warnings.each do |w|
if w.severity == :deprecation
# Do *not* call Puppet.deprecation_warning it is for internal deprecation, not
# deprecation of constructs in manifests! (It is not designed for that purpose even if
# used throughout the code base).
#
log_message(:warning, formatter, w) if emitted_dw < max_deprecations
emitted_dw += 1
else
log_message(:warning, formatter, w) if emitted_w < max_warnings
emitted_w += 1
end
break if emitted_w >= max_warnings && emitted_dw >= max_deprecations # but only then
end
end
# If there were errors, report the first found. Use a puppet style formatter.
errors = acceptor.errors
if errors.size > 0
unless emit_errors
raise emit_exception, emit_message
end
formatter = Validation::DiagnosticFormatterPuppetStyle.new
if errors.size == 1 || max_errors <= 1
# raise immediately
exception = create_exception(emit_exception, emit_message, formatter, errors[0])
# if an exception was given as cause, use it's backtrace instead of the one indicating "here"
if errors[0].exception
exception.set_backtrace(errors[0].exception.backtrace)
end
raise exception
end
emitted = 0
if emit_message
Puppet.err(emit_message)
end
errors.each do |e|
log_message(:err, formatter, e)
emitted += 1
break if emitted >= max_errors
end
giving_up_message = if emit_warnings && warnings.size > 0
_("Language validation logged %{error_count} errors, and %{warning_count} warnings. Giving up") %
{ error_count: errors.size, warning_count: warnings.size }
else
_("Language validation logged %{error_count} errors. Giving up") %
{ error_count: errors.size }
end
exception = emit_exception.new(giving_up_message)
exception.file = errors[0].file
raise exception
end
end
def self.format_with_prefix(prefix, message)
return message unless prefix
[prefix, message].join(' ')
end
def self.warning(semantic, issue, args)
Puppet::Util::Log.create({
:level => :warning,
:message => issue.format(args),
:arguments => args,
:issue_code => issue.issue_code,
:file => semantic.file,
:line => semantic.line,
:pos => semantic.pos,
})
end
def self.error(exception_class, semantic, issue, args)
raise exception_class.new(issue.format(args), semantic.file, semantic.line, semantic.pos, nil, issue.issue_code, args)
end
def self.create_exception(exception_class, emit_message, formatter, diagnostic)
file = diagnostic.file
file = (file.is_a?(String) && file.empty?) ? nil : file
line = pos = nil
if diagnostic.source_pos
line = diagnostic.source_pos.line
pos = diagnostic.source_pos.pos
end
exception_class.new(format_with_prefix(emit_message, formatter.format_message(diagnostic)), file, line, pos, nil, diagnostic.issue.issue_code, diagnostic.arguments)
end
private_class_method :create_exception
def self.log_message(severity, formatter, diagnostic)
file = diagnostic.file
file = (file.is_a?(String) && file.empty?) ? nil : file
line = pos = nil
if diagnostic.source_pos
line = diagnostic.source_pos.line
pos = diagnostic.source_pos.pos
end
Puppet::Util::Log.create({
:level => severity,
:message => formatter.format_message(diagnostic),
:arguments => diagnostic.arguments,
:issue_code => diagnostic.issue.issue_code,
:file => file,
:line => line,
:pos => pos,
})
end
private_class_method :log_message
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/validation/tasks_checker.rb | lib/puppet/pops/validation/tasks_checker.rb | # frozen_string_literal: true
module Puppet::Pops
module Validation
# Validator that limits the set of allowed expressions to not include catalog related operations
# @api private
class TasksChecker < Checker4_0
def in_ApplyExpression?
top = container(0)
step = -1
until container(step) == top
return true if container(step).is_a? Puppet::Pops::Model::ApplyBlockExpression
step -= 1
end
end
def check_CollectExpression(o)
# Only virtual resource queries are allowed in apply blocks, not exported
# resource queries
if in_ApplyExpression?
if o.query.is_a?(Puppet::Pops::Model::VirtualQuery)
super(o)
else
acceptor.accept(Issues::EXPRESSION_NOT_SUPPORTED_WHEN_COMPILING, o, { :klass => o })
end
else
illegalTasksExpression(o)
end
end
def check_HostClassDefinition(o)
illegalTasksExpression(o)
end
def check_NodeDefinition(o)
if in_ApplyExpression?
super(o)
else
illegalTasksExpression(o)
end
end
def check_RelationshipExpression(o)
if in_ApplyExpression?
super(o)
else
illegalTasksExpression(o)
end
end
def check_ResourceDefaultsExpression(o)
if in_ApplyExpression?
super(o)
else
illegalTasksExpression(o)
end
end
def check_ResourceExpression(o)
if in_ApplyExpression?
super(o)
else
illegalTasksExpression(o)
end
end
def check_ResourceOverrideExpression(o)
if in_ApplyExpression?
super(o)
else
illegalTasksExpression(o)
end
end
def check_ResourceTypeDefinition(o)
illegalTasksExpression(o)
end
def check_ApplyExpression(o)
if in_ApplyExpression?
acceptor.accept(Issues::EXPRESSION_NOT_SUPPORTED_WHEN_COMPILING, o, { :klass => o })
end
end
def illegalTasksExpression(o)
acceptor.accept(Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING, o, { :klass => o })
end
def resource_without_title?(o)
false
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/validation/validator_factory_4_0.rb | lib/puppet/pops/validation/validator_factory_4_0.rb | # frozen_string_literal: true
module Puppet::Pops
module Validation
# Configures validation suitable for 4.0
#
class ValidatorFactory_4_0 < Factory
# Produces the checker to use
def checker diagnostic_producer
if Puppet[:tasks]
require_relative 'tasks_checker'
TasksChecker.new(diagnostic_producer)
else
Checker4_0.new(diagnostic_producer)
end
end
# Produces the label provider to use
def label_provider
Model::ModelLabelProvider.new()
end
# Produces the severity producer to use
def severity_producer
p = super
# Configure each issue that should **not** be an error
#
# Validate as per the current runtime configuration
p[Issues::RT_NO_STORECONFIGS_EXPORT] = Puppet[:storeconfigs] ? :ignore : :warning
p[Issues::RT_NO_STORECONFIGS] = Puppet[:storeconfigs] ? :ignore : :warning
p[Issues::FUTURE_RESERVED_WORD] = :deprecation
p[Issues::DUPLICATE_KEY] = Puppet[:strict] == :off ? :ignore : Puppet[:strict]
p[Issues::NAME_WITH_HYPHEN] = :error
p[Issues::EMPTY_RESOURCE_SPECIALIZATION] = :ignore
p[Issues::CLASS_NOT_VIRTUALIZABLE] = :error
p[Issues::ILLEGAL_NONLITERAL_PARAMETER_TYPE] = :deprecation
p
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/validation/checker4_0.rb | lib/puppet/pops/validation/checker4_0.rb | # frozen_string_literal: true
require_relative '../../../puppet/pops/evaluator/external_syntax_support'
module Puppet::Pops
module Validation
# A Validator validates a model.
#
# Validation is performed on each model element in isolation. Each method should validate the model element's state
# but not validate its referenced/contained elements except to check their validity in their respective role.
# The intent is to drive the validation with a tree iterator that visits all elements in a model.
#
#
# TODO: Add validation of multiplicities - this is a general validation that can be checked for all
# Model objects via their metamodel. (I.e an extra call to multiplicity check in polymorph check).
# This is however mostly valuable when validating model to model transformations, and is therefore T.B.D
#
class Checker4_0 < Evaluator::LiteralEvaluator
include Puppet::Pops::Evaluator::ExternalSyntaxSupport
attr_reader :acceptor
attr_reader :migration_checker
def self.check_visitor
# Class instance variable rather than Class variable because methods visited
# may be overridden in subclass
@check_visitor ||= Visitor.new(nil, 'check', 0, 0)
end
# Initializes the validator with a diagnostics producer. This object must respond to
# `:will_accept?` and `:accept`.
#
def initialize(diagnostics_producer)
super()
@@rvalue_visitor ||= Visitor.new(nil, "rvalue", 0, 0)
@@hostname_visitor ||= Visitor.new(nil, "hostname", 1, 2)
@@assignment_visitor ||= Visitor.new(nil, "assign", 0, 1)
@@query_visitor ||= Visitor.new(nil, "query", 0, 0)
@@relation_visitor ||= Visitor.new(nil, "relation", 0, 0)
@@idem_visitor ||= Visitor.new(nil, "idem", 0, 0)
@check_visitor = self.class.check_visitor
@acceptor = diagnostics_producer
# Use null migration checker unless given in context
@migration_checker = Puppet.lookup(:migration_checker) { Migration::MigrationChecker.new() }
end
# Validates the entire model by visiting each model element and calling `check`.
# The result is collected (or acted on immediately) by the configured diagnostic provider/acceptor
# given when creating this Checker.
#
def validate(model)
# tree iterate the model, and call check for each element
@path = []
check(model)
internal_check_top_construct_in_module(model)
model._pcore_all_contents(@path) { |element| check(element) }
end
def container(index = -1)
@path[index]
end
# Performs regular validity check
def check(o)
@check_visitor.visit_this_0(self, o)
end
# Performs check if this is a vaid hostname expression
# @param single_feature_name [String, nil] the name of a single valued hostname feature of the value's container. e.g. 'parent'
def hostname(o, semantic)
@@hostname_visitor.visit_this_1(self, o, semantic)
end
# Performs check if this is valid as a query
def query(o)
@@query_visitor.visit_this_0(self, o)
end
# Performs check if this is valid as a relationship side
def relation(o)
@@relation_visitor.visit_this_0(self, o)
end
# Performs check if this is valid as a rvalue
def rvalue(o)
@@rvalue_visitor.visit_this_0(self, o)
end
#---TOP CHECK
# Performs check if this is valid as a container of a definition (class, define, node)
def top(definition, idx = -1)
o = container(idx)
idx -= 1
case o
when NilClass, Model::ApplyExpression, Model::HostClassDefinition, Model::Program
# ok, stop scanning parents
when Model::BlockExpression
c = container(idx)
if !c.is_a?(Model::Program) &&
(definition.is_a?(Model::FunctionDefinition) || definition.is_a?(Model::TypeAlias) || definition.is_a?(Model::TypeDefinition))
# not ok. These can never be nested in a block
acceptor.accept(Issues::NOT_ABSOLUTE_TOP_LEVEL, definition)
else
# ok, if this is a block representing the body of a class, or is top level
top(definition, idx)
end
when Model::LambdaExpression
# A LambdaExpression is a BlockExpression, and this check is needed to prevent the polymorph method for BlockExpression
# to accept a lambda.
# A lambda can not iteratively create classes, nodes or defines as the lambda does not have a closure.
acceptor.accept(Issues::NOT_TOP_LEVEL, definition)
else
# fail, reached a container that is not top level
acceptor.accept(Issues::NOT_TOP_LEVEL, definition)
end
end
# Checks the LHS of an assignment (is it assignable?).
# If args[0] is true, assignment via index is checked.
#
def assign(o, via_index = false)
@@assignment_visitor.visit_this_1(self, o, via_index)
end
# Checks if the expression has side effect ('idem' is latin for 'the same', here meaning that the evaluation state
# is known to be unchanged after the expression has been evaluated). The result is not 100% authoritative for
# negative answers since analysis of function behavior is not possible.
# @return [Boolean] true if expression is known to have no effect on evaluation state
#
def idem(o)
@@idem_visitor.visit_this_0(self, o)
end
# Returns the last expression in a block, or the expression, if that expression is idem
def ends_with_idem(o)
if o.is_a?(Model::BlockExpression)
last = o.statements[-1]
idem(last) ? last : nil
else
idem(o) ? o : nil
end
end
#---ASSIGNMENT CHECKS
def assign_VariableExpression(o, via_index)
varname_string = varname_to_s(o.expr)
if varname_string =~ Patterns::NUMERIC_VAR_NAME
acceptor.accept(Issues::ILLEGAL_NUMERIC_ASSIGNMENT, o, :varname => varname_string)
end
# Can not assign to something in another namespace (i.e. a '::' in the name is not legal)
if acceptor.will_accept? Issues::CROSS_SCOPE_ASSIGNMENT
if varname_string =~ /::/
acceptor.accept(Issues::CROSS_SCOPE_ASSIGNMENT, o, :name => varname_string)
end
end
# TODO: Could scan for reassignment of the same variable if done earlier in the same container
# Or if assigning to a parameter (more work).
end
def assign_AccessExpression(o, via_index)
# Are indexed assignments allowed at all ? $x[x] = '...'
if acceptor.will_accept? Issues::ILLEGAL_INDEXED_ASSIGNMENT
acceptor.accept(Issues::ILLEGAL_INDEXED_ASSIGNMENT, o)
else
# Then the left expression must be assignable-via-index
assign(o.left_expr, true)
end
end
def assign_LiteralList(o, via_index)
o.values.each { |x| assign(x) }
end
def assign_Object(o, via_index)
# Can not assign to anything else (differentiate if this is via index or not)
# i.e. 10 = 'hello' vs. 10['x'] = 'hello' (the root is reported as being in error in both cases)
#
acceptor.accept(via_index ? Issues::ILLEGAL_ASSIGNMENT_VIA_INDEX : Issues::ILLEGAL_ASSIGNMENT, o)
end
#---CHECKS
def check_Object(o)
end
def check_Factory(o)
check(o.model)
end
def check_AccessExpression(o)
# Only min range is checked, all other checks are RT checks as they depend on the resulting type
# of the LHS.
if o.keys.size < 1
acceptor.accept(Issues::MISSING_INDEX, o)
end
end
def check_AssignmentExpression(o)
case o.operator
when '='
assign(o.left_expr)
rvalue(o.right_expr)
when '+=', '-='
acceptor.accept(Issues::APPENDS_DELETES_NO_LONGER_SUPPORTED, o, { :operator => o.operator })
else
acceptor.accept(Issues::UNSUPPORTED_OPERATOR, o, { :operator => o.operator })
end
end
# Checks that operation with :+> is contained in a ResourceOverride or Collector.
#
# Parent of an AttributeOperation can be one of:
# * CollectExpression
# * ResourceOverride
# * ResourceBody (ILLEGAL this is a regular resource expression)
# * ResourceDefaults (ILLEGAL)
#
def check_AttributeOperation(o)
if o.operator == '+>'
# Append operator use is constrained
p = container
unless p.is_a?(Model::CollectExpression) || p.is_a?(Model::ResourceOverrideExpression)
acceptor.accept(Issues::ILLEGAL_ATTRIBUTE_APPEND, o, { :name => o.attribute_name, :parent => p })
end
end
rvalue(o.value_expr)
end
def check_AttributesOperation(o)
# Append operator use is constrained
p = container
case p
when Model::AbstractResource
# do nothing
when Model::CollectExpression
# do nothing
else
# protect against just testing a snippet that has no parent, error message will be a bit strange
# but it is not for a real program.
parent2 = p.nil? ? o : container(-2)
unless parent2.is_a?(Model::AbstractResource)
acceptor.accept(Issues::UNSUPPORTED_OPERATOR_IN_CONTEXT, parent2, :operator => '* =>')
end
end
rvalue(o.expr)
end
def check_BinaryExpression(o)
rvalue(o.left_expr)
rvalue(o.right_expr)
end
def resource_without_title?(o)
if o.instance_of?(Model::BlockExpression)
statements = o.statements
statements.length == 2 && statements[0].instance_of?(Model::QualifiedName) && statements[1].instance_of?(Model::LiteralHash)
else
false
end
end
def check_BlockExpression(o)
if resource_without_title?(o)
acceptor.accept(Issues::RESOURCE_WITHOUT_TITLE, o, :name => o.statements[0].value)
else
o.statements[0..-2].each do |statement|
if idem(statement)
acceptor.accept(Issues::IDEM_EXPRESSION_NOT_LAST, statement)
break # only flag the first
end
end
end
end
def check_CallNamedFunctionExpression(o)
functor = o.functor_expr
if functor.is_a?(Model::QualifiedReference) ||
functor.is_a?(Model::AccessExpression) && functor.left_expr.is_a?(Model::QualifiedReference)
# ok (a call to a type)
return nil
end
case functor
when Model::QualifiedName
# ok
nil
when Model::RenderStringExpression
# helpful to point out this easy to make Epp error
acceptor.accept(Issues::ILLEGAL_EPP_PARAMETERS, o)
else
acceptor.accept(Issues::ILLEGAL_EXPRESSION, o.functor_expr, { :feature => 'function name', :container => o })
end
end
def check_EppExpression(o)
p = container
if p.is_a?(Model::LambdaExpression)
internal_check_no_capture(p, o)
internal_check_parameter_name_uniqueness(p)
end
end
def check_HeredocExpression(o)
# Only syntax check static text in heredoc during validation - dynamic text is validated by the evaluator.
expr = o.text_expr
if expr.is_a?(Model::LiteralString)
assert_external_syntax(nil, expr.value, o.syntax, o.text_expr)
end
end
def check_MethodCallExpression(o)
unless o.functor_expr.is_a? Model::QualifiedName
acceptor.accept(Issues::ILLEGAL_EXPRESSION, o.functor_expr, :feature => 'function name', :container => o)
end
end
def check_CaseExpression(o)
rvalue(o.test)
# There can only be one LiteralDefault case option value
found_default = false
o.options.each do |option|
option.values.each do |value|
next unless value.is_a?(Model::LiteralDefault)
# Flag the second default as 'unreachable'
acceptor.accept(Issues::DUPLICATE_DEFAULT, value, :container => o) if found_default
found_default = true
end
end
end
def check_CaseOption(o)
o.values.each { |v| rvalue(v) }
end
def check_CollectExpression(o)
unless o.type_expr.is_a? Model::QualifiedReference
acceptor.accept(Issues::ILLEGAL_EXPRESSION, o.type_expr, :feature => 'type name', :container => o)
end
end
# Only used for function names, grammar should not be able to produce something faulty, but
# check anyway if model is created programmatically (it will fail in transformation to AST for sure).
def check_NamedAccessExpression(o)
name = o.right_expr
unless name.is_a? Model::QualifiedName
acceptor.accept(Issues::ILLEGAL_EXPRESSION, name, :feature => 'function name', :container => container)
end
end
RESERVED_TYPE_NAMES = {
'type' => true,
'any' => true,
'unit' => true,
'scalar' => true,
'boolean' => true,
'numeric' => true,
'integer' => true,
'float' => true,
'collection' => true,
'array' => true,
'hash' => true,
'tuple' => true,
'struct' => true,
'variant' => true,
'optional' => true,
'enum' => true,
'regexp' => true,
'pattern' => true,
'runtime' => true,
'init' => true,
'object' => true,
'sensitive' => true,
'semver' => true,
'semverrange' => true,
'string' => true,
'timestamp' => true,
'timespan' => true,
'typeset' => true,
}
FUTURE_RESERVED_WORDS = {
'plan' => true
}
# for 'class', 'define', and function
def check_NamedDefinition(o)
top(o)
if o.name !~ Patterns::CLASSREF_DECL
acceptor.accept(Issues::ILLEGAL_DEFINITION_NAME, o, { :name => o.name })
end
internal_check_file_namespace(o)
internal_check_reserved_type_name(o, o.name)
internal_check_future_reserved_word(o, o.name)
end
def check_TypeAlias(o)
top(o)
if o.name !~ Patterns::CLASSREF_EXT_DECL
acceptor.accept(Issues::ILLEGAL_DEFINITION_NAME, o, { :name => o.name })
end
internal_check_reserved_type_name(o, o.name)
internal_check_type_ref(o, o.type_expr)
end
def check_TypeMapping(o)
top(o)
lhs = o.type_expr
lhs_type = 0 # Not Runtime
if lhs.is_a?(Model::AccessExpression)
left = lhs.left_expr
if left.is_a?(Model::QualifiedReference) && left.cased_value == 'Runtime'
lhs_type = 1 # Runtime
keys = lhs.keys
# Must be a literal string or pattern replacement
lhs_type = 2 if keys.size == 2 && pattern_with_replacement?(keys[1])
end
end
if lhs_type == 0
# This is not a TypeMapping. Something other than Runtime[] on LHS
acceptor.accept(Issues::UNSUPPORTED_EXPRESSION, o)
else
rhs = o.mapping_expr
if pattern_with_replacement?(rhs)
acceptor.accept(Issues::ILLEGAL_SINGLE_TYPE_MAPPING, o) if lhs_type == 1
elsif type_ref?(rhs)
acceptor.accept(Issues::ILLEGAL_REGEXP_TYPE_MAPPING, o) if lhs_type == 2
else
acceptor.accept(lhs_type == 1 ? Issues::ILLEGAL_SINGLE_TYPE_MAPPING : Issues::ILLEGAL_REGEXP_TYPE_MAPPING, o)
end
end
end
def pattern_with_replacement?(o)
if o.is_a?(Model::LiteralList)
v = o.values
v.size == 2 && v[0].is_a?(Model::LiteralRegularExpression) && v[1].is_a?(Model::LiteralString)
else
false
end
end
def type_ref?(o)
o = o.left_expr if o.is_a?(Model::AccessExpression)
o.is_a?(Model::QualifiedReference)
end
def check_TypeDefinition(o)
top(o)
internal_check_reserved_type_name(o, o.name)
# TODO: Check TypeDefinition body. For now, just error out
acceptor.accept(Issues::UNSUPPORTED_EXPRESSION, o)
end
def check_FunctionDefinition(o)
check_NamedDefinition(o)
internal_check_return_type(o)
internal_check_parameter_name_uniqueness(o)
end
def check_HostClassDefinition(o)
check_NamedDefinition(o)
internal_check_no_capture(o)
internal_check_parameter_name_uniqueness(o)
internal_check_reserved_params(o)
internal_check_no_idem_last(o)
internal_check_parameter_type_literal(o)
end
def check_ResourceTypeDefinition(o)
check_NamedDefinition(o)
internal_check_no_capture(o)
internal_check_parameter_name_uniqueness(o)
internal_check_reserved_params(o)
internal_check_no_idem_last(o)
end
def internal_check_parameter_type_literal(o)
o.parameters.each do |p|
next unless p.type_expr
type = nil
catch :not_literal do
type = literal(p.type_expr)
end
acceptor.accept(Issues::ILLEGAL_NONLITERAL_PARAMETER_TYPE, p, { name: p.name, type_class: p.type_expr.class }) if type.nil?
end
end
def internal_check_return_type(o)
r = o.return_type
internal_check_type_ref(o, r) unless r.nil?
end
def internal_check_type_ref(o, r)
n = r.is_a?(Model::AccessExpression) ? r.left_expr : r
if n.is_a? Model::QualifiedReference
internal_check_future_reserved_word(r, n.value)
else
acceptor.accept(Issues::ILLEGAL_EXPRESSION, r, :feature => 'a type reference', :container => o)
end
end
def internal_check_no_idem_last(o)
violator = ends_with_idem(o.body)
if violator
acceptor.accept(Issues::IDEM_NOT_ALLOWED_LAST, violator, { :container => o }) unless resource_without_title?(violator)
end
end
def internal_check_capture_last(o)
accepted_index = o.parameters.size() - 1
o.parameters.each_with_index do |p, index|
if p.captures_rest && index != accepted_index
acceptor.accept(Issues::CAPTURES_REST_NOT_LAST, p, { :param_name => p.name })
end
end
end
def internal_check_no_capture(o, container = o)
o.parameters.each do |p|
if p.captures_rest
acceptor.accept(Issues::CAPTURES_REST_NOT_SUPPORTED, p, { :container => container, :param_name => p.name })
end
end
end
def internal_check_reserved_type_name(o, name)
if RESERVED_TYPE_NAMES[name]
acceptor.accept(Issues::RESERVED_TYPE_NAME, o, { :name => name })
end
end
def internal_check_future_reserved_word(o, name)
if FUTURE_RESERVED_WORDS[name]
acceptor.accept(Issues::FUTURE_RESERVED_WORD, o, { :word => name })
end
end
NO_NAMESPACE = :no_namespace
NO_PATH = :no_path
BAD_MODULE_FILE = :bad_module_file
def internal_check_file_namespace(o)
file = o.locator.file
return if file.nil? || file == '' # e.g. puppet apply -e '...'
file_namespace = namespace_for_file(file)
return if file_namespace == NO_NAMESPACE
# Downcasing here because check is case-insensitive
if file_namespace == BAD_MODULE_FILE || !o.name.downcase.start_with?(file_namespace)
acceptor.accept(Issues::ILLEGAL_DEFINITION_LOCATION, o, { :name => o.name, :file => file })
end
end
def internal_check_top_construct_in_module(prog)
return unless prog.is_a?(Model::Program) && !prog.body.nil?
# Check that this is a module autoloaded file
file = prog.locator.file
return if file.nil?
return if namespace_for_file(file) == NO_NAMESPACE
body = prog.body
return if prog.body.is_a?(Model::Nop) # Ignore empty or comment-only files
if body.is_a?(Model::BlockExpression)
body.statements.each { |s| acceptor.accept(Issues::ILLEGAL_TOP_CONSTRUCT_LOCATION, s) unless valid_top_construct?(s) }
else
acceptor.accept(Issues::ILLEGAL_TOP_CONSTRUCT_LOCATION, body) unless valid_top_construct?(body)
end
end
def valid_top_construct?(o)
o.is_a?(Model::Definition) && !o.is_a?(Model::NodeDefinition)
end
# @api private
class Puppet::Util::FileNamespaceAdapter < Puppet::Pops::Adaptable::Adapter
attr_accessor :file_to_namespace
def self.create_adapter(env)
adapter = super(env)
adapter.file_to_namespace = {}
adapter
end
end
def namespace_for_file(file)
env = Puppet.lookup(:current_environment)
return NO_NAMESPACE if env.nil?
adapter = Puppet::Util::FileNamespaceAdapter.adapt(env)
file_namespace = adapter.file_to_namespace[file]
return file_namespace unless file_namespace.nil? # No cache entry, so we do the calculation
path = Pathname.new(file)
return adapter.file_to_namespace[file] = NO_NAMESPACE if path.extname != ".pp"
path = path.expand_path
return adapter.file_to_namespace[file] = NO_NAMESPACE if initial_manifest?(path, env.manifest)
# All auto-loaded files from modules come from a module search path dir
relative_path = get_module_relative_path(path, env.full_modulepath)
return adapter.file_to_namespace[file] = NO_NAMESPACE if relative_path == NO_PATH
# If a file comes from a module, but isn't in the right place, always error
names = dir_to_names(relative_path)
adapter.file_to_namespace[file] = (names == BAD_MODULE_FILE ? BAD_MODULE_FILE : names.join("::").freeze)
end
def initial_manifest?(path, manifest_setting)
return false if manifest_setting.nil? || manifest_setting == :no_manifest
string_path = path.to_s
string_path == manifest_setting || string_path.start_with?(manifest_setting)
end
# Get the path of +file_path+ relative to the first directory in
# +modulepath_directories+ that is an ancestor of +file_path+. Return NO_PATH
# if none is found.
def get_module_relative_path(file_path, modulepath_directories)
clean_file = file_path.cleanpath.to_s
parent_path = modulepath_directories.find { |path_dir| is_parent_dir_of?(path_dir, clean_file) }
return NO_PATH if parent_path.nil?
file_path.relative_path_from(Pathname.new(parent_path))
end
private :get_module_relative_path
def is_parent_dir_of?(parent_dir, child_dir)
parent_dir_path = Pathname.new(parent_dir)
clean_parent = parent_dir_path.cleanpath.to_s + File::SEPARATOR
child_dir.start_with?(clean_parent)
end
private :is_parent_dir_of?
def dir_to_names(relative_path)
# Downcasing here because check is case-insensitive
path_components = relative_path.to_s.downcase.split(File::SEPARATOR)
# Example definition dir: manifests in this path:
# <module name>/manifests/<module subdir>/<classfile>.pp
dir = path_components[1]
# How can we get this result?
# If it is not an initial manifest, it must come from a module,
# and from the manifests dir there. This may never get used...
return BAD_MODULE_FILE unless dir == 'manifests' || dir == 'functions' || dir == 'types' || dir == 'plans'
names = path_components[2..-2] # Directories inside module
names.unshift(path_components[0]) # Name of the module itself
# Do not include name of module init file at top level of module
# e.g. <module name>/manifests/init.pp
filename = path_components[-1]
unless path_components.length == 3 && filename == 'init.pp'
names.push(filename[0..-4]) # Remove .pp from filename
end
names
end
RESERVED_PARAMETERS = {
'name' => true,
'title' => true,
}
def internal_check_reserved_params(o)
o.parameters.each do |p|
if RESERVED_PARAMETERS[p.name]
acceptor.accept(Issues::RESERVED_PARAMETER, p, { :container => o, :param_name => p.name })
end
end
end
def internal_check_parameter_name_uniqueness(o)
unique = Set.new
o.parameters.each do |p|
acceptor.accept(Issues::DUPLICATE_PARAMETER, p, { :param_name => p.name }) unless unique.add?(p.name)
end
end
def check_IfExpression(o)
rvalue(o.test)
end
def check_KeyedEntry(o)
rvalue(o.key)
rvalue(o.value)
# In case there are additional things to forbid than non-rvalues
# acceptor.accept(Issues::ILLEGAL_EXPRESSION, o.key, :feature => 'hash key', :container => container)
end
def check_LambdaExpression(o)
internal_check_capture_last(o)
internal_check_return_type(o)
end
def check_LiteralList(o)
o.values.each { |v| rvalue(v) }
end
def check_LiteralInteger(o)
v = o.value
if v < MIN_INTEGER || v > MAX_INTEGER
acceptor.accept(Issues::NUMERIC_OVERFLOW, o, { :value => v })
end
end
def check_LiteralHash(o)
# the keys of a literal hash may be non-literal expressions. They cannot be checked.
unique = Set.new
o.entries.each do |entry|
catch(:not_literal) do
literal_key = literal(entry.key)
acceptor.accept(Issues::DUPLICATE_KEY, entry, { :key => literal_key }) if unique.add?(literal_key).nil?
end
end
end
def check_NodeDefinition(o)
# Check that hostnames are valid hostnames (or regular expressions)
hostname(o.host_matches, o)
top(o)
violator = ends_with_idem(o.body)
if violator
acceptor.accept(Issues::IDEM_NOT_ALLOWED_LAST, violator, { :container => o }) unless resource_without_title?(violator)
end
unless o.parent.nil?
acceptor.accept(Issues::ILLEGAL_NODE_INHERITANCE, o.parent)
end
end
# No checking takes place - all expressions using a QualifiedName need to check. This because the
# rules are slightly different depending on the container (A variable allows a numeric start, but not
# other names). This means that (if the lexer/parser so chooses) a QualifiedName
# can be anything when it represents a Bare Word and evaluates to a String.
#
def check_QualifiedName(o)
end
# Checks that the value is a valid UpperCaseWord (a CLASSREF), and optionally if it contains a hypen.
# DOH: QualifiedReferences are created with LOWER CASE NAMES at parse time
def check_QualifiedReference(o)
# Is this a valid qualified name?
if o.cased_value !~ Patterns::CLASSREF_EXT
acceptor.accept(Issues::ILLEGAL_CLASSREF, o, { :name => o.cased_value })
end
end
def check_QueryExpression(o)
query(o.expr) if o.expr # is optional
end
def relation_Object(o)
rvalue(o)
end
def relation_CollectExpression(o); end
def relation_RelationshipExpression(o); end
def check_Parameter(o)
if o.name =~ /^(?:0x)?[0-9]+$/
acceptor.accept(Issues::ILLEGAL_NUMERIC_PARAMETER, o, :name => o.name)
end
unless o.name =~ Patterns::PARAM_NAME
acceptor.accept(Issues::ILLEGAL_PARAM_NAME, o, :name => o.name)
end
return unless o.value
internal_check_illegal_assignment(o.value)
end
def internal_check_illegal_assignment(o)
if o.is_a?(Model::AssignmentExpression)
acceptor.accept(Issues::ILLEGAL_ASSIGNMENT_CONTEXT, o)
else
# recursively check all contents unless it's a lambda expression. A lambda may contain
# local assignments
o._pcore_contents { |model| internal_check_illegal_assignment(model) } unless o.is_a?(Model::LambdaExpression)
end
end
# relationship_side: resource
# | resourceref
# | collection
# | variable
# | quotedtext
# | selector
# | casestatement
# | hasharrayaccesses
def check_RelationshipExpression(o)
relation(o.left_expr)
relation(o.right_expr)
end
def check_ResourceExpression(o)
# The expression for type name cannot be statically checked - this is instead done at runtime
# to enable better error message of the result of the expression rather than the static instruction.
# (This can be revised as there are static constructs that are illegal, but require updating many
# tests that expect the detailed reporting).
type_name_expr = o.type_name
if o.form && o.form != 'regular' && type_name_expr.is_a?(Model::QualifiedName) && type_name_expr.value == 'class'
acceptor.accept(Issues::CLASS_NOT_VIRTUALIZABLE, o)
end
end
def check_ResourceBody(o)
seenUnfolding = false
o.operations.each do |ao|
if ao.is_a?(Model::AttributesOperation)
if seenUnfolding
acceptor.accept(Issues::MULTIPLE_ATTRIBUTES_UNFOLD, ao)
else
seenUnfolding = true
end
end
end
end
def check_ResourceDefaultsExpression(o)
if o.form != 'regular'
acceptor.accept(Issues::NOT_VIRTUALIZEABLE, o)
end
end
def check_ResourceOverrideExpression(o)
if o.form != 'regular'
acceptor.accept(Issues::NOT_VIRTUALIZEABLE, o)
end
end
def check_ReservedWord(o)
if o.future
acceptor.accept(Issues::FUTURE_RESERVED_WORD, o, :word => o.word)
else
acceptor.accept(Issues::RESERVED_WORD, o, :word => o.word)
end
end
def check_SelectorExpression(o)
rvalue(o.left_expr)
# There can only be one LiteralDefault case option value
defaults = o.selectors.select { |v| v.matching_expr.is_a?(Model::LiteralDefault) }
unless defaults.size <= 1
# Flag the second default as 'unreachable'
acceptor.accept(Issues::DUPLICATE_DEFAULT, defaults[1].matching_expr, :container => o)
end
end
def check_SelectorEntry(o)
rvalue(o.matching_expr)
end
def check_UnaryExpression(o)
rvalue(o.expr)
end
def check_UnlessExpression(o)
rvalue(o.test)
# TODO: Unless may not have an else part that is an IfExpression (grammar denies this though)
end
# Checks that variable is either strictly 0, or a non 0 starting decimal number, or a valid VAR_NAME
def check_VariableExpression(o)
# The expression must be a qualified name or an integer
name_expr = o.expr
return if name_expr.is_a?(Model::LiteralInteger)
if !name_expr.is_a?(Model::QualifiedName)
acceptor.accept(Issues::ILLEGAL_EXPRESSION, o, :feature => 'name', :container => o)
else
# name must be either a decimal string value, or a valid NAME
name = o.expr.value
if name[0, 1] =~ /[0-9]/
unless name =~ Patterns::NUMERIC_VAR_NAME
acceptor.accept(Issues::ILLEGAL_NUMERIC_VAR_NAME, o, :name => name)
end
else
unless name =~ Patterns::VAR_NAME
acceptor.accept(Issues::ILLEGAL_VAR_NAME, o, :name => name)
end
end
end
end
#--- HOSTNAME CHECKS
# Transforms Array of host matching expressions into a (Ruby) array of AST::HostName
def hostname_Array(o, semantic)
o.each { |x| hostname(x, semantic) }
end
def hostname_String(o, semantic)
# The 3.x checker only checks for illegal characters - if matching /[^-\w.]/ the name is invalid,
# but this allows pathological names like "a..b......c", "----"
# TODO: Investigate if more illegal hostnames should be flagged.
#
if o =~ Patterns::ILLEGAL_HOSTNAME_CHARS
acceptor.accept(Issues::ILLEGAL_HOSTNAME_CHARS, semantic, :hostname => o)
end
end
def hostname_LiteralValue(o, semantic)
hostname_String(o.value.to_s, o)
end
def hostname_ConcatenatedString(o, semantic)
# Puppet 3.1. only accepts a concatenated string without interpolated expressions
the_expr = o.segments.index { |s| s.is_a?(Model::TextExpression) }
if the_expr
acceptor.accept(Issues::ILLEGAL_HOSTNAME_INTERPOLATION, o.segments[the_expr].expr)
elsif o.segments.size() != 1
# corner case, bad model, concatenation of several plain strings
acceptor.accept(Issues::ILLEGAL_HOSTNAME_INTERPOLATION, o)
else
# corner case, may be ok, but lexer may have replaced with plain string, this is
# here if it does not
hostname_String(o.segments[0], o.segments[0])
end
end
def hostname_QualifiedName(o, semantic)
hostname_String(o.value.to_s, o)
end
def hostname_QualifiedReference(o, semantic)
hostname_String(o.value.to_s, o)
end
def hostname_LiteralNumber(o, semantic)
# always ok
end
def hostname_LiteralDefault(o, semantic)
# always ok
end
def hostname_LiteralRegularExpression(o, semantic)
# always ok
end
def hostname_Object(o, semantic)
acceptor.accept(Issues::ILLEGAL_EXPRESSION, o, { :feature => 'hostname', :container => semantic })
end
#---QUERY CHECKS
# Anything not explicitly allowed is flagged as error.
def query_Object(o)
acceptor.accept(Issues::ILLEGAL_QUERY_EXPRESSION, o)
end
# Puppet AST only allows == and !=
#
def query_ComparisonExpression(o)
acceptor.accept(Issues::ILLEGAL_QUERY_EXPRESSION, o) unless ['==', '!='].include? o.operator
end
# Allows AND, OR, and checks if left/right are allowed in query.
def query_BooleanExpression(o)
query o.left_expr
query o.right_expr
end
def query_ParenthesizedExpression(o)
query(o.expr)
end
def query_VariableExpression(o); end
def query_QualifiedName(o); end
def query_LiteralNumber(o); end
def query_LiteralString(o); end
def query_LiteralBoolean(o); end
#---RVALUE CHECKS
# By default, all expressions are reported as being rvalues
# Implement specific rvalue checks for those that are not.
#
def rvalue_Expression(o); end
def rvalue_CollectExpression(o)
acceptor.accept(Issues::NOT_RVALUE, o)
end
def rvalue_Definition(o)
acceptor.accept(Issues::NOT_RVALUE, o)
end
def rvalue_NodeDefinition(o)
acceptor.accept(Issues::NOT_RVALUE, o)
end
def rvalue_UnaryExpression(o)
rvalue o.expr
end
#--IDEM CHECK
def idem_Object(o)
false
end
def idem_Nop(o)
true
end
def idem_NilClass(o)
true
end
def idem_Literal(o)
true
end
def idem_LiteralList(o)
true
end
def idem_LiteralHash(o)
true
end
def idem_Factory(o)
idem(o.model)
end
def idem_AccessExpression(o)
true
end
def idem_BinaryExpression(o)
true
end
def idem_MatchExpression(o)
false # can have side effect of setting $n match variables
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/resource/param.rb | lib/puppet/pops/resource/param.rb | # frozen_string_literal: true
# An implementation of the interface Puppet::Resource
# that adapts the 3.x compiler and catalog expectations on
# a resource instance. This instance is backed by a
# pcore representation of the resource type an instance of this
# ruby class.
#
# This class must inherit from Puppet::Resource because of the
# class expectations in existing logic.
#
# This implementation does not support
# * setting 'strict' - strictness (must refer to an existing type) is always true
# * does not support the indirector
#
#
module Puppet::Pops
module Resource
class Param
# This make this class instantiable from Puppet
include Puppet::Pops::Types::PuppetObject
def self.register_ptype(loader, ir)
@ptype = Pcore.create_object_type(loader, ir, self, 'Puppet::Resource::Param', nil,
{
Types::KEY_TYPE => Types::PTypeType::DEFAULT,
Types::KEY_NAME => Types::PStringType::NON_EMPTY,
'name_var' => {
Types::KEY_TYPE => Types::PBooleanType::DEFAULT,
Types::KEY_VALUE => false
}
},
EMPTY_HASH,
[Types::KEY_NAME])
end
attr_reader :name
attr_reader :type
attr_reader :name_var
def initialize(type, name, name_var = false)
@type = type
@name = name
@name_var = name_var
end
def to_s
name
end
def self._pcore_type
@ptype
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/resource/resource_type_impl.rb | lib/puppet/pops/resource/resource_type_impl.rb | # frozen_string_literal: true
require_relative 'param'
module Puppet::Pops
module Resource
def self.register_ptypes(loader, ir)
types = [Param, ResourceTypeImpl].map do |c|
c.register_ptype(loader, ir)
end
types.each { |t| t.resolve(loader) }
end
class ResourceTypeImpl
# Make instances of this class directly creatable from the Puppet Language
# as object.
#
include Puppet::Pops::Types::PuppetObject
# Instances of ResourceTypeImpl can be used as the type of a Puppet::Parser::Resource/Puppet::Resource when compiling
#
include Puppet::CompilableResourceType
# Returns the Puppet Type for this instance.
def self._pcore_type
@ptype
end
def self.register_ptype(loader, ir)
param_ref = Types::PTypeReferenceType.new('Puppet::Resource::Param')
@ptype = Pcore.create_object_type(loader, ir, self, 'Puppet::Resource::ResourceType3', nil,
{
Types::KEY_NAME => Types::PStringType::NON_EMPTY,
'properties' => {
Types::KEY_TYPE => Types::PArrayType.new(param_ref),
Types::KEY_VALUE => EMPTY_ARRAY
},
'parameters' => {
Types::KEY_TYPE => Types::PArrayType.new(param_ref),
Types::KEY_VALUE => EMPTY_ARRAY
},
'title_patterns_hash' => {
Types::KEY_TYPE => Types::POptionalType.new(
Types::PHashType.new(Types::PRegexpType::DEFAULT, Types::PArrayType.new(Types::PStringType::NON_EMPTY))
),
Types::KEY_VALUE => nil
},
'isomorphic' => {
Types::KEY_TYPE => Types::PBooleanType::DEFAULT,
Types::KEY_VALUE => true
},
'capability' => {
Types::KEY_TYPE => Types::PBooleanType::DEFAULT,
Types::KEY_VALUE => false
},
},
EMPTY_HASH,
[Types::KEY_NAME])
end
def eql?(other)
other.is_a?(Puppet::CompilableResourceType) && @name == other.name
end
alias == eql?
# Compares this type against the given _other_ (type) and returns -1, 0, or +1 depending on the order.
# @param other [Object] the object to compare against (produces nil, if not kind of Type}
# @return [-1, 0, +1, nil] produces -1 if this type is before the given _other_ type, 0 if equals, and 1 if after.
# Returns nil, if the given _other_ is not a kind of Type.
# @see Comparable
#
def <=>(other)
# Order is only maintained against other types, not arbitrary objects.
# The natural order is based on the reference name used when comparing
return nil unless other.is_a?(Puppet::CompilableResourceType)
# against other type instances.
ref <=> other.ref
end
METAPARAMS = [
:noop,
:schedule,
:audit,
:loglevel,
:alias,
:tag,
:require,
:subscribe,
:before,
:notify,
:stage
].freeze
# Speed up lookup
METAPARAMSET = Set.new(METAPARAMS).freeze
attr_reader :name
attr_reader :properties
attr_reader :parameters
attr_reader :title_patterns_hash
attr_reader :title_patterns
def initialize(name, properties = EMPTY_ARRAY, parameters = EMPTY_ARRAY, title_patterns_hash = nil, isomorphic = true, capability = false)
@name = name
@properties = properties
@parameters = parameters
@title_patterns_hash = title_patterns_hash
@isomorphic = isomorphic
# ignore capability parameter
# Compute attributes hash
# Compute key_names (possibly compound key if there are multiple name vars).
@attributes = {}
@key_attributes = []
# Name to kind of attribute
@attr_types = {}
# Add all meta params
METAPARAMS.each { |p| @attr_types[p] = :meta }
@property_set = Set.new(properties.map do |p|
symname = p.name.to_sym
@attributes[symname] = p
@key_attributes << symname if p.name_var
@attr_types[symname] = :property
symname
end).freeze
@param_set = Set.new(parameters.map do |p|
symname = p.name.to_sym
@attributes[symname] = p
@key_attributes << symname if p.name_var
@attr_types[symname] = :param
symname
end).freeze
# API for title patterns is [ [regexp, [ [ [sym, <lambda>], [sym, <lambda>] ] ] ] ]
# Where lambdas are optional. This resource type impl does not support lambdas
# Note that the pcore file has a simpler hashmap that is post processed here
# since the structure must have Symbol instances for names which the .pp representation
# does not deliver.
#
@title_patterns =
case @key_attributes.length
when 0
# TechDebt: The case of specifying title patterns when having no name vars is unspecified behavior in puppet
# Here it is silently ignored.
nil
when 1
if @title_patterns_hash.nil?
[[/(.*)/m, [[@key_attributes.first]]]]
else
# TechDebt: The case of having one namevar and an empty title patterns is unspecified behavior in puppet.
# Here, it may lead to an empty map which may or may not trigger the wanted/expected behavior.
#
@title_patterns_hash.map { |k, v| [k, v.map { |n| [n.to_sym] }] }
end
else
if @title_patterns_hash.nil? || @title_patterns_hash.empty?
# TechDebt: While title patterns must be specified when more than one is used, they do not have
# to match/set them all since some namevars can be omitted (to support the use case in
# the 'package' type where 'provider' attribute is handled as part of the key without being
# set from the title.
#
raise Puppet::DevError, _("you must specify title patterns when there are two or more key attributes")
end
@title_patterns_hash.nil? ? [] : @title_patterns_hash.map { |k, v| [k, v.map { |n| [n.to_sym] }] }
end
end
# Override CompilableResource inclusion
def is_3x_ruby_plugin?
false
end
# Answers if the parameter name is a parameter/attribute of this type
# This is part of the Puppet::Type API
# Check if used when compiling (it is triggered in an apply)
#
def valid_parameter?(name)
@attributes.include?(name) || METAPARAMSET.include?(name)
end
# The type implementation of finish does a lot of things
# * iterates over all parameters and calls post_compile on them if the parameter impl responds to post_compile
# * validates the relationship parameters
#
# This implementation does nothing - it is assumed that the catalog is already validated
# via the relationship validator (done late in the game).
def finish
# Do nothing.
end
# This is called on a resource type
# it performs tagging if it is a Class or Node.
# It also ensure the parent type is in the catalog, but that is weird since
# resource types cannot really inherit
def instantiate_resource(scope, resource)
# Do nothing because nothing is needed when compiling.
# This is what the Puppet::Type implementation does
# None of this should be needed
# # Make sure our parent class has been evaluated, if we have one.
# if parent && !scope.catalog.resource(resource.type, parent)
# parent_type(scope).ensure_in_catalog(scope)
# end
# This will never happen
# if ['Class', 'Node'].include? resource.type
# scope.catalog.tag(*resource.tags)
# end
end
# Being isomorphic in puppet means that the resource is managing a state
# (as opposed to a resource like Exec that is a function, possibly with side effect.
# In a Ruby implementation of a resource type, @isomorphic = false is used to turn
# off isomorphism, it is true by default.
# This is part of the Puppet::Type API.
#
def isomorphic?
@isomorphic
end
# Produces the names of the attributes that make out the unique id of a resource
#
def key_attributes
@key_attributes
end
# Gives a type a chance to issue deprecations for parameters.
# @param title [String] the title of the resource of this type
# @param attributes [Array<Param>] the set parameters in the resource instance
def deprecate_params(title, attributes)
# TODO: Current API somewhat unclear, if done at type level, or per
# Param.
end
##################################################
# NEVER CALLED COMPILE SIDE FOR A COMPILATION
##################################################
# Answers :property, :param or :meta depending on the type of the attribute
# According to original version, this is called millions of times
# and a cache is required.
# @param name [Symbol]
def attrtype(name)
raise NotImplementedError, "attrtype() - returns the kind (:meta, :param, or :property) of the parameter"
# @attr_types[name]
end
# Returns the implementation of a param/property/attribute - i.e. a Param class
def attrclass(name)
raise NotImplementedError, "attrclass() - returns the (param) class of the parameter"
end
# PROBABLY NOT USED WHEN COMPILING
# Returns the names of all attributes in a defined order:
# * all key attributes (the composite id)
# * :provider if it is specified
# * all properties
# * all parameters
# * meta parameters
#
def allattrs
raise NotImplementedError, "allattrs() - return all attribute names in order - probably not used master side"
# key_attributes | (parameters & [:provider]) | properties.collect { |property| property.name } | parameters | metaparams
end
# Sets "applies to host"
def apply_to
raise NotImplementedError, "apply_to() - probably used when selecting a provider (device/host support)"
end
def apply_to_host
raise NotImplementedError, "apply_to_host() - probably used when selecting a provider (device/host support)"
end
def apply_to_device
raise NotImplementedError, "apply_to_device() - probably used when selecting a provider (device/host support)"
end
def apply_to_all
raise NotImplementedError, "apply_to_all() - probably used when selecting a provider (device/host support)"
end
def can_apply_to_target(target)
raise NotImplementedError, "can_apply_to_target() - probably used when selecting a provider (device/host support)"
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/loader/puppet_plan_instantiator.rb | lib/puppet/pops/loader/puppet_plan_instantiator.rb | # frozen_string_literal: true
module Puppet::Pops
module Loader
# The PuppetPlanInstantiator instantiates a Puppet::Functions::PuppetFunction given a Puppet Programming language
# source that when called evaluates the Puppet logic it contains.
#
class PuppetPlanInstantiator
# Produces an instance of the Function class with the given typed_name, or fails with an error if the
# given puppet source does not produce this instance when evaluated.
#
# @param loader [Loader] The loader the function is associated with
# @param typed_name [TypedName] the type / name of the function to load
# @param source_ref [URI, String] a reference to the source / origin of the puppet code to evaluate
# @param pp_code_string [String] puppet code in a string
#
# @return [Functions::Function] - an instantiated function with global scope closure associated with the given loader
#
def self.create(loader, typed_name, source_ref, pp_code_string)
parser = Parser::EvaluatingParser.new()
# parse and validate
result = parser.parse_string(pp_code_string, source_ref)
# The parser attaches all definitions, including those nested in apply
# blocks, to the Program object. Node definitions in apply blocks are
# perfectly legal and don't count as the file containing multiple
# definitions for this purpose. By this point, we've already validated that
# there are no node definitions *outside* apply blocks, so we simply ignore
# them here.
definitions = result.definitions.reject { |definition| definition.is_a?(Puppet::Pops::Model::NodeDefinition) }
# Only one plan is allowed (and no other definitions)
case definitions.size
when 0
raise ArgumentError, _("The code loaded from %{source_ref} does not define the plan '%{plan_name}' - it is empty.") % { source_ref: source_ref, plan_name: typed_name.name }
when 1
# ok
else
raise ArgumentError, _("The code loaded from %{source_ref} must contain only the plan '%{plan_name}' - it has additional definitions.") % { source_ref: source_ref, plan_name: typed_name.name }
end
the_plan_definition = definitions[0]
unless the_plan_definition.is_a?(Model::PlanDefinition)
raise ArgumentError, _("The code loaded from %{source_ref} does not define the plan '%{plan_name}' - no plan found.") % { source_ref: source_ref, plan_name: typed_name.name }
end
unless the_plan_definition.name == typed_name.name
expected = typed_name.name
actual = the_plan_definition.name
raise ArgumentError, _("The code loaded from %{source_ref} produced plan with the wrong name, expected %{expected}, actual %{actual}") % { source_ref: source_ref, expected: expected, actual: actual }
end
unless result.body == the_plan_definition
raise ArgumentError, _("The code loaded from %{source} contains additional logic - can only contain the plan %{plan_name}") % { source: source_ref, plan_name: typed_name.name }
end
# Adapt the function definition with loader - this is used from logic contained in it body to find the
# loader to use when making calls to the new function 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(the_plan_definition).loader_name = private_loader.loader_name
# Cannot bind loaded functions to global scope, that must be done without binding that scope as
# loaders survive a compilation.
closure_scope = nil
created = create_function_class(the_plan_definition)
# 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
created.new(closure_scope, private_loader)
end
# Creates Function class and instantiates it based on a FunctionDefinition model
# @return [Array<TypedName, Functions.Function>] - array of
# typed name, and an instantiated function with global scope closure associated with the given loader
#
def self.create_from_model(plan_definition, loader)
created = create_function_class(plan_definition)
typed_name = TypedName.new(:plan, plan_definition.name)
[typed_name, created.new(nil, loader)]
end
def self.create_function_class(plan_definition)
# Create a 4x function wrapper around a named closure
Puppet::Functions.create_function(plan_definition.name, Puppet::Functions::PuppetFunction) do
# TODO: should not create a new evaluator per function
init_dispatch(Evaluator::Closure::Named.new(
plan_definition.name,
Evaluator::EvaluatorImpl.new(), plan_definition
))
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/loader/static_loader.rb | lib/puppet/pops/loader/static_loader.rb | # frozen_string_literal: true
# Static Loader contains constants, basic data types and other types required for the system
# to boot.
#
module Puppet::Pops
module Loader
class StaticLoader < Loader
BUILTIN_TYPE_NAMES = %w[
Component
Exec
File
Filebucket
Group
Node
Notify
Package
Resources
Schedule
Service
Stage
Tidy
User
Whit
].freeze
BUILTIN_TYPE_NAMES_LC = Set.new(BUILTIN_TYPE_NAMES.map(&:downcase)).freeze
BUILTIN_ALIASES = {
'Data' => 'Variant[ScalarData,Undef,Hash[String,Data],Array[Data]]',
'RichDataKey' => 'Variant[String,Numeric]',
'RichData' => 'Variant[Scalar,SemVerRange,Binary,Sensitive,Type,TypeSet,URI,Object,Undef,Default,Hash[RichDataKey,RichData],Array[RichData]]',
# Backward compatible aliases.
'Puppet::LookupKey' => 'RichDataKey',
'Puppet::LookupValue' => 'RichData'
}.freeze
attr_reader :loaded
def initialize
@loaded = {}
@runtime_3_initialized = false
create_built_in_types
end
def discover(type, error_collector = nil, name_authority = Pcore::RUNTIME_NAME_AUTHORITY)
# Static loader only contains runtime types
return EMPTY_ARRAY unless type == :type && name_authority == Pcore::RUNTIME_NAME_AUTHORITY
typed_names = @loaded.keys
block_given? ? typed_names.select { |tn| yield(tn) } : typed_names
end
def load_typed(typed_name)
load_constant(typed_name)
end
def get_entry(typed_name)
load_constant(typed_name)
end
def set_entry(typed_name, value, origin = nil)
@loaded[typed_name] = Loader::NamedEntry.new(typed_name, value, origin)
end
def find(name)
# There is nothing to search for, everything this loader knows about is already available
nil
end
def parent
nil # at top of the hierarchy
end
def to_s
"(StaticLoader)"
end
def loaded_entry(typed_name, check_dependencies = false)
@loaded[typed_name]
end
def runtime_3_init
unless @runtime_3_initialized
@runtime_3_initialized = true
create_resource_type_references
end
nil
end
def register_aliases
aliases = BUILTIN_ALIASES.map { |name, string| add_type(name, Types::PTypeAliasType.new(name, Types::TypeFactory.type_reference(string), nil)) }
aliases.each { |type| type.resolve(self) }
end
private
def load_constant(typed_name)
@loaded[typed_name]
end
def create_built_in_types
origin_uri = URI("puppet:Puppet-Type-System/Static-Loader")
type_map = Puppet::Pops::Types::TypeParser.type_map
type_map.each do |name, type|
set_entry(TypedName.new(:type, name), type, origin_uri)
end
end
def create_resource_type_references
# These needs to be done quickly and we do not want to scan the file system for these
# We are also not interested in their definition only that they exist.
# These types are in all environments.
#
BUILTIN_TYPE_NAMES.each { |name| create_resource_type_reference(name) }
end
def add_type(name, type)
set_entry(TypedName.new(:type, name), type)
type
end
def create_resource_type_reference(name)
add_type(name, Types::TypeFactory.resource(name))
end
def synchronize(&block)
yield
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/loader/dependency_loader.rb | lib/puppet/pops/loader/dependency_loader.rb | # frozen_string_literal: true
# =DependencyLoader
# This loader provides visibility into a set of other loaders. It is used as a child of a ModuleLoader (or other
# loader) to make its direct dependencies visible for loading from contexts that have access to this dependency loader.
# Access is typically given to logic that resides inside of the module, but not to those that just depend on the module.
#
# It is instantiated with a name, and with a set of dependency_loaders.
#
# @api private
#
class Puppet::Pops::Loader::DependencyLoader < Puppet::Pops::Loader::BaseLoader
# Creates a DependencyLoader for one parent loader
#
# @param parent_loader [Puppet::Pops::Loader] typically a module loader for the root
# @param name [String] the name of the dependency-loader (used for debugging and tracing only)
# @param dependency_loaders [Array<Puppet::Pops::Loader>] array of loaders for modules this module depends on
#
def initialize(parent_loader, name, dependency_loaders, environment)
super(parent_loader, name, environment)
@dependency_loaders = dependency_loaders
end
def discover(type, error_collector = nil, name_authority = Puppet::Pops::Pcore::RUNTIME_NAME_AUTHORITY, &block)
result = []
@dependency_loaders.each { |loader| result.concat(loader.discover(type, error_collector, name_authority, &block)) }
result.concat(super)
result
end
# Finds name in a loader this loader depends on / can see
#
def find(typed_name)
if typed_name.qualified?
l = index()[typed_name.name_parts[0]]
if l
l.load_typed(typed_name)
else
# no module entered as dependency with name matching first segment of wanted name
nil
end
else
# a non name-spaced name, have to search since it can be anywhere.
# (Note: superclass caches the result in this loader as it would have to repeat this search for every
# lookup otherwise).
loaded = @dependency_loaders.reduce(nil) do |previous, loader|
break previous unless previous.nil?
loader.load_typed(typed_name)
end
if loaded
promote_entry(loaded)
end
loaded
end
end
# @api public
#
def loaded_entry(typed_name, check_dependencies = false)
super || (check_dependencies ? loaded_entry_in_dependency(typed_name, check_dependencies) : nil)
end
def to_s
"(DependencyLoader '#{@loader_name}' [" + @dependency_loaders.map(&:to_s).join(' ,') + "])"
end
private
def loaded_entry_in_dependency(typed_name, check_dependencies)
if typed_name.qualified?
l = index[typed_name.name_parts[0]]
if l
l.loaded_entry(typed_name)
else
# no module entered as dependency with name matching first segment of wanted name
nil
end
else
# a non name-spaced name, have to search since it can be anywhere.
# (Note: superclass caches the result in this loader as it would have to repeat this search for every
# lookup otherwise).
@dependency_loaders.reduce(nil) do |previous, loader|
break previous unless previous.nil?
loader.loaded_entry(typed_name, check_dependencies)
end
end
end
# An index of module_name to module loader used to speed up lookup of qualified names
def index
@index ||= @dependency_loaders.each_with_object({}) { |loader, index| index[loader.module_name] = loader; }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/loader/puppet_function_instantiator.rb | lib/puppet/pops/loader/puppet_function_instantiator.rb | # frozen_string_literal: true
module Puppet::Pops
module Loader
# The PuppetFunctionInstantiator instantiates a Puppet::Functions::PuppetFunction given a Puppet Programming language
# source that when called evaluates the Puppet logic it contains.
#
class PuppetFunctionInstantiator
# Produces an instance of the Function class with the given typed_name, or fails with an error if the
# given puppet source does not produce this instance when evaluated.
#
# @param loader [Loader] The loader the function is associated with
# @param typed_name [TypedName] the type / name of the function to load
# @param source_ref [URI, String] a reference to the source / origin of the puppet code to evaluate
# @param pp_code_string [String] puppet code in a string
#
# @return [Functions::Function] - an instantiated function with global scope closure associated with the given loader
#
def self.create(loader, typed_name, source_ref, pp_code_string)
parser = Parser::EvaluatingParser.new()
# parse and validate
result = parser.parse_string(pp_code_string, source_ref)
# Only one function is allowed (and no other definitions)
case result.definitions.size
when 0
raise ArgumentError, _("The code loaded from %{source_ref} does not define the function '%{func_name}' - it is empty.") % { source_ref: source_ref, func_name: typed_name.name }
when 1
# ok
else
raise ArgumentError, _("The code loaded from %{source_ref} must contain only the function '%{type_name}' - it has additional definitions.") % { source_ref: source_ref, type_name: typed_name.name }
end
the_function_definition = result.definitions[0]
unless the_function_definition.is_a?(Model::FunctionDefinition)
raise ArgumentError, _("The code loaded from %{source_ref} does not define the function '%{type_name}' - no function found.") % { source_ref: source_ref, type_name: typed_name.name }
end
unless the_function_definition.name == typed_name.name
expected = typed_name.name
actual = the_function_definition.name
raise ArgumentError, _("The code loaded from %{source_ref} produced function with the wrong name, expected %{expected}, actual %{actual}") % { source_ref: source_ref, expected: expected, actual: actual }
end
unless result.body == the_function_definition
raise ArgumentError, _("The code loaded from %{source} contains additional logic - can only contain the function %{name}") % { source: source_ref, name: typed_name.name }
end
# Adapt the function definition with loader - this is used from logic contained in it body to find the
# loader to use when making calls to the new function 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(the_function_definition).loader_name = private_loader.loader_name
# Cannot bind loaded functions to global scope, that must be done without binding that scope as
# loaders survive a compilation.
closure_scope = nil # Puppet.lookup(:global_scope) { {} }
created = create_function_class(the_function_definition)
# 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
created.new(closure_scope, private_loader)
end
# Creates Function class and instantiates it based on a FunctionDefinition model
# @return [Array<TypedName, Functions.Function>] - array of
# typed name, and an instantiated function with global scope closure associated with the given loader
#
def self.create_from_model(function_definition, loader)
created = create_function_class(function_definition)
typed_name = TypedName.new(:function, function_definition.name)
[typed_name, created.new(nil, loader)]
end
def self.create_function_class(function_definition)
# Create a 4x function wrapper around a named closure
Puppet::Functions.create_function(function_definition.name, Puppet::Functions::PuppetFunction) do
# TODO: should not create a new evaluator per function
init_dispatch(Evaluator::Closure::Named.new(
function_definition.name,
Evaluator::EvaluatorImpl.new(), function_definition
))
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/loader/module_loaders.rb | lib/puppet/pops/loader/module_loaders.rb | # frozen_string_literal: true
module Puppet::Pops
module Loader
# =ModuleLoaders
# A ModuleLoader loads items from a single module.
# The ModuleLoaders (ruby) module contains various such loaders. There is currently one concrete
# implementation, ModuleLoaders::FileBased that loads content from the file system.
# Other implementations can be created - if they are based on name to path mapping where the path
# is relative to a root path, they can derive the base behavior from the ModuleLoaders::AbstractPathBasedModuleLoader class.
#
# Examples of such extensions could be a zip/jar/compressed file base loader.
#
# Notably, a ModuleLoader does not configure itself - it is given the information it needs (the root, its name etc.)
# Logic higher up in the loader hierarchy of things makes decisions based on the "shape of modules", and "available
# modules" to determine which module loader to use for each individual module. (There could be differences in
# internal layout etc.)
#
# A module loader is also not aware of the mapping of name to relative paths.
#
# @api private
#
module ModuleLoaders
# Wildcard module name for module loaders, makes loading possible from any namespace.
NAMESPACE_WILDCARD = '*'
# This is exactly the same as the #system_loader_from method, but the argument for path is changed to
# location where pluginsync stores functions. It also accepts definitions in any namespace since pluginsync
# places all of them in the same directory.
#
def self.cached_loader_from(parent_loader, loaders)
LibRootedFileBased.new(parent_loader,
loaders,
NAMESPACE_WILDCARD,
Puppet[:libdir],
'cached_puppet_lib',
[:func_4x, :func_3x, :datatype])
end
def self.system_loader_from(parent_loader, loaders)
# Puppet system may be installed in a fixed location via RPM, installed as a Gem, via source etc.
# The only way to find this across the different ways puppet can be installed is
# to search up the path from this source file's __FILE__ location until it finds the base of
# puppet.
#
puppet_lib = File.realpath(File.join(File.dirname(__FILE__), '../../..'))
LibRootedFileBased.new(parent_loader,
loaders,
nil,
puppet_lib, # may or may not have a 'lib' above 'puppet'
'puppet_system',
[:func_4x, :func_3x, :datatype]) # only load ruby functions and types from "puppet"
end
def self.environment_loader_from(parent_loader, loaders, env_path)
if env_path.nil? || env_path.empty?
EmptyLoader.new(parent_loader, ENVIRONMENT, loaders.environment)
else
FileBased.new(parent_loader,
loaders,
ENVIRONMENT,
env_path,
ENVIRONMENT)
end
end
def self.module_loader_from(parent_loader, loaders, module_name, module_path)
ModuleLoaders::FileBased.new(parent_loader,
loaders,
module_name,
module_path,
module_name)
end
def self.pcore_resource_type_loader_from(parent_loader, loaders, environment_path)
ModuleLoaders::FileBased.new(parent_loader,
loaders,
nil,
environment_path,
'pcore_resource_types')
end
class EmptyLoader < BaseLoader
def find(typed_name)
nil
end
def private_loader
@private_loader ||= self
end
def private_loader=(loader)
@private_loader = loader
end
end
class AbstractPathBasedModuleLoader < BaseLoader
# The name of the module, or nil, if this is a global "component", or "any module" if set to the `NAMESPACE_WILDCARD` (*)
attr_reader :module_name
# The path to the location of the module/component - semantics determined by subclass
attr_reader :path
# A map of type to smart-paths that help with minimizing the number of paths to scan
attr_reader :smart_paths
# A Module Loader has a private loader, it is lazily obtained on request to provide the visibility
# for entities contained in the module. Since a ModuleLoader also represents an environment and it is
# created a different way, this loader can be set explicitly by the loaders bootstrap logic.
#
# @api private
attr_writer :private_loader
# Initialize a kind of ModuleLoader for one module
# @param parent_loader [Loader] loader with higher priority
# @param loaders [Loaders] the container for this loader
# @param module_name [String] the name of the module (non qualified name), may be nil for a global "component"
# @param path [String] the path to the root of the module (semantics defined by subclass)
# @param loader_name [String] a name that is used for human identification (useful when module_name is nil)
#
def initialize(parent_loader, loaders, module_name, path, loader_name, loadables)
super(parent_loader, loader_name, loaders.environment)
raise ArgumentError, 'path based loader cannot be instantiated without a path' if path.nil? || path.empty?
@module_name = module_name
@path = path
@smart_paths = LoaderPaths::SmartPaths.new(self)
@loaders = loaders
@loadables = loadables
unless (loadables - LOADABLE_KINDS).empty?
# TRANSLATORS 'loadables' is a variable containing loadable modules and should not be translated
raise ArgumentError, _('given loadables are not of supported loadable kind')
end
loaders.add_loader_by_name(self)
end
def loadables
@loadables
end
def discover(type, error_collector = nil, name_authority = Pcore::RUNTIME_NAME_AUTHORITY, &block)
global = global?
if name_authority == Pcore::RUNTIME_NAME_AUTHORITY
smart_paths.effective_paths(type).each do |sp|
relative_paths(sp).each do |rp|
tp = sp.typed_name(type, name_authority, rp, global ? nil : @module_name)
next unless sp.valid_name?(tp)
begin
load_typed(tp) unless block_given? && !block.yield(tp)
rescue StandardError => e
if error_collector.nil?
Puppet.warn_once(:unloadable_entity, tp.to_s, e.message)
else
err = Puppet::DataTypes::Error.new(
Issues::LOADER_FAILURE.format(:type => type),
'PUPPET_LOADER_FAILURE',
{ 'original_error' => e.message },
Issues::LOADER_FAILURE.issue_code
)
error_collector << err unless error_collector.include?(err)
end
end
end
end
end
super
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)
# This loader is tailored to only find entries in the current runtime
return nil unless typed_name.name_authority == Pcore::RUNTIME_NAME_AUTHORITY
# Assume it is a global name, and that all parts of the name should be used when looking up
name_parts = typed_name.name_parts
# Certain types and names can be disqualified up front
if name_parts.size > 1
# The name is in a name space.
# Then entity cannot possible be in this module unless the name starts with the module name.
# Note:
# * If "module" represents a "global component", the module_name is nil and cannot match which is
# ok since such a "module" cannot have namespaced content).
# * If this loader is allowed to have namespaced content, the module_name can be set to NAMESPACE_WILDCARD `*`
#
return nil unless name_parts[0] == module_name || module_name == NAMESPACE_WILDCARD
else
# The name is in the global name space.
case typed_name.type
when :function, :resource_type, :resource_type_pp
# Can be defined in module using a global name. No action required
when :plan
unless global?
# Global name must be the name of the module
return nil unless name_parts[0] == module_name
# Look for the special 'init' plan.
origin, smart_path = find_existing_path(init_plan_name)
return smart_path.nil? ? nil : instantiate(smart_path, typed_name, origin)
end
when :task
unless global?
# Global name must be the name of the module
return nil unless name_parts[0] == module_name
# Look for the special 'init' Task
origin, smart_path = find_existing_path(init_task_name)
return smart_path.nil? ? nil : instantiate(smart_path, typed_name, origin)
end
when :type
unless global?
# Global name must be the name of the module
unless name_parts[0] == module_name || module_name == NAMESPACE_WILDCARD
# Check for ruby defined data type in global namespace before giving up
origin, smart_path = find_existing_path(typed_name)
return smart_path.is_a?(LoaderPaths::DataTypePath) ? instantiate(smart_path, typed_name, origin) : nil
end
# Look for the special 'init_typeset' TypeSet
origin, smart_path = find_existing_path(init_typeset_name)
return nil if smart_path.nil?
value = smart_path.instantiator.create(self, typed_name, origin, get_contents(origin))
if value.is_a?(Types::PTypeSetType)
# cache the entry and return it
return set_entry(typed_name, value, origin)
end
# TRANSLATORS 'TypeSet' should not be translated
raise ArgumentError, _("The code loaded from %{origin} does not define the TypeSet '%{module_name}'") %
{ origin: origin, module_name: name_parts[0].capitalize }
end
else
# anything else cannot possibly be in this module
# TODO: should not be allowed anyway... may have to revisit this decision
return nil
end
end
# Get the paths that actually exist in this module (they are lazily processed once and cached).
# The result is an array (that may be empty).
# Find the file to instantiate, and instantiate the entity if file is found
origin, smart_path = find_existing_path(typed_name)
return instantiate(smart_path, typed_name, origin) unless smart_path.nil?
return nil unless typed_name.type == :type && typed_name.qualified?
# Search for TypeSet using parent name
ts_name = typed_name.parent
while ts_name
# Do not traverse parents here. This search must be confined to this loader
tse = get_entry(ts_name)
tse = find(ts_name) if tse.nil? || tse.value.nil?
if tse && (ts = tse.value).is_a?(Types::PTypeSetType)
# The TypeSet might be unresolved at this point. If so, it must be resolved using
# this loader. That in turn, adds all contained types to this loader.
ts.resolve(self)
te = get_entry(typed_name)
return te unless te.nil?
end
ts_name = ts_name.parent
end
nil
end
def instantiate(smart_path, typed_name, origin)
if origin.is_a?(Array)
value = smart_path.instantiator.create(self, typed_name, origin)
else
value = smart_path.instantiator.create(self, typed_name, origin, get_contents(origin))
end
# cache the entry and return it
set_entry(typed_name, value, origin)
end
# Abstract method that subclasses override that checks if it is meaningful to search using a generic smart path.
# This optimization is performed to not be tricked into searching an empty directory over and over again.
# The implementation may perform a deep search for file content other than directories and cache this in
# and index. It is guaranteed that a call to meaningful_to_search? takes place before checking any other
# path with relative_path_exists?.
#
# This optimization exists because many modules have been created from a template and they have
# empty directories for functions, types, etc. (It is also the place to create a cached index of the content).
#
# @param smart_path [String] a path relative to the module's root
# @return [Boolean] true if there is content in the directory appointed by the relative path
#
def meaningful_to_search?(smart_path)
raise NotImplementedError
end
# Abstract method that subclasses override to answer if the given relative path exists, and if so returns that path
#
# @param resolved_path [String] a path resolved by a smart path against the loader's root (if it has one)
# @return [String, nil] the found path or nil if no such path was found
#
def existing_path(resolved_path)
raise NotImplementedError
end
# Abstract method that subclasses override to return an array of paths that may be associated with the resolved path.
#
# @param resolved_path [String] a path, without extension, resolved by a smart path against the loader's root (if it has one)
# @return [Array<String>]
#
def candidate_paths(resolved_path)
raise NotImplementedError
end
# Abstract method that subclasses override to produce the content of the effective path.
# It should either succeed and return a String or fail with an exception.
#
# @param effective_path [String] a path as resolved by a smart path
# @return [String] the content of the file
#
def get_contents(effective_path)
raise NotImplementedError
end
# Abstract method that subclasses override to produce a source reference String used to identify the
# system resource (resource in the URI sense).
#
# @param relative_path [String] a path relative to the module's root
# @return [String] a reference to the source file (in file system, zip file, or elsewhere).
#
def get_source_ref(relative_path)
raise NotImplementedError
end
# Answers the question if this loader represents a global component (true for resource type loader and environment loader)
#
# @return [Boolean] `true` if this loader represents a global component
#
def global?
module_name.nil? || module_name == NAMESPACE_WILDCARD || module_name == ENVIRONMENT
end
# Answers `true` if the loader used by this instance is rooted beneath 'lib'. This is
# typically true for the system_loader. It will have a path relative to the parent
# of 'puppet' instead of the parent of 'lib/puppet' since the 'lib' directory of puppet
# is renamed during install. This is significant for loaders that load ruby code.
#
# @return [Boolean] a boolean answering if the loader is rooted beneath 'lib'.
def lib_root?
false
end
# Produces the private loader for the module. If this module is not already resolved, this will trigger resolution
#
def private_loader
# The system loader has a nil module_name and it does not have a private_loader as there are no functions
# that can only by called by puppet runtime - if so, it acts as the private loader directly.
@private_loader ||= (global? ? self : @loaders.private_loader_for_module(module_name))
end
# Return all paths that matches the given smart path. The returned paths are
# relative to the `#generic_path` of the given smart path.
#
# @param smart_path [SmartPath] the path to find relative paths for
# @return [Array<String>] found paths
def relative_paths(smart_path)
raise NotImplementedError
end
private
# @return [TypedName] the fake typed name that maps to the init_typeset path for this module
def init_typeset_name
@init_typeset_name ||= TypedName.new(:type, "#{module_name}::init_typeset")
end
# @return [TypedName] the fake typed name that maps to the path of an init[arbitrary extension]
# file that represents a task named after the module
def init_task_name
@init_task_name ||= TypedName.new(:task, "#{module_name}::init")
end
# @return [TypedName] the fake typed name that maps to the path of an init.pp file that represents
# a plan named after the module
def init_plan_name
@init_plan_name ||= TypedName.new(:plan, "#{module_name}::init")
end
# Find an existing path or paths for the given `typed_name`. Return `nil` if no path is found
# @param typed_name [TypedName] the `typed_name` to find a path for
# @return [Array,nil] `nil`or a two element array where the first element is an effective path or array of paths
# (depending on the `SmartPath`) and the second element is the `SmartPath` that produced the effective path or
# paths. A path is a String
def find_existing_path(typed_name)
is_global = global?
smart_paths.effective_paths(typed_name.type).each do |sp|
next unless sp.valid_name?(typed_name)
origin = sp.effective_path(typed_name, is_global ? 0 : 1)
unless origin.nil?
if sp.fuzzy_matching?
# If there are multiple *specific* paths for the file, find
# whichever ones exist. Otherwise, find all paths that *might* be
# related to origin
if origin.is_a?(Array)
origins = origin.filter_map { |ori| existing_path(ori) }
else
origins = candidate_paths(origin)
end
return [origins, sp] unless origins.empty?
else
existing = existing_path(origin)
return [origin, sp] unless existing.nil?
end
end
end
nil
end
end
# @api private
#
class FileBased < AbstractPathBasedModuleLoader
attr_reader :smart_paths
attr_reader :path_index
# Create a kind of ModuleLoader for one module (Puppet Module, or module like)
#
# @param parent_loader [Loader] typically the loader for the environment or root
# @param module_name [String] the name of the module (non qualified name), may be nil for "modules" only containing globals
# @param path [String] the path to the root of the module (semantics defined by subclass)
# @param loader_name [String] a name that identifies the loader
#
def initialize(parent_loader, loaders, module_name, path, loader_name, loadables = LOADABLE_KINDS)
super
@path_index = Set.new
end
def existing_path(effective_path)
# Optimized, checks index instead of visiting file system
@path_index.include?(effective_path) ? effective_path : nil
end
def candidate_paths(effective_path)
basename = File.basename(effective_path, '.*')
dirname = File.dirname(effective_path)
files = @path_index.select do |path|
File.dirname(path) == dirname
end
# At least one file has to match what we're loading, or it certainly doesn't exist
if files.any? { |file| File.basename(file, '.*') == basename }
files
else
[]
end
end
def meaningful_to_search?(smart_path)
!add_to_index(smart_path).empty?
end
def to_s
"(ModuleLoader::FileBased '#{loader_name}' '#{module_name}')"
end
def add_to_index(smart_path)
found = Dir.glob(File.join(smart_path.generic_path, '**', "*#{smart_path.extension}"))
# The reason for not always rejecting directories here is performance (avoid extra stat calls). The
# false positives (directories with a matching extension) is an error in any case and will be caught
# later.
found = found.reject { |file_name| File.directory?(file_name) } if smart_path.extension.empty?
@path_index.merge(found)
found
end
def get_contents(effective_path)
Puppet::FileSystem.read(effective_path, :encoding => 'utf-8')
end
# Return all paths that matches the given smart path. The returned paths are
# relative to the `#generic_path` of the given smart path.
#
# This method relies on the cache and does not perform any file system access
#
# @param smart_path [SmartPath] the path to find relative paths for
# @return [Array<String>] found paths
def relative_paths(smart_path)
root = smart_path.generic_path
found = []
@path_index.each do |path|
found << Pathname(path).relative_path_from(Pathname(root)).to_s if smart_path.valid_path?(path)
end
found
end
end
# Specialization used by the system_loader which is limited to see what's beneath 'lib' and hence
# cannot be rooted in its parent. The 'lib' directory is renamed during install so any attempt
# to traverse into it from above would fail.
#
# @api private
#
class LibRootedFileBased < FileBased
def lib_root?
true
end
end
# Loads from a gem specified as a URI, gem://gemname/optional/path/in/gem, or just a String gemname.
# The source reference (shown in errors etc.) is the expanded path of the gem as this is believed to be more
# helpful - given the location it should be quite obvious which gem it is, without the location, the user would
# need to go on a hunt for where the file actually is located.
#
# TODO: How does this get instantiated? Does the gemname refelect the name of the module (the namespace)
# or is that specified a different way? Can a gem be the container of multiple modules?
#
# @api private
#
class GemBased < FileBased
include GemSupport
attr_reader :gem_ref
# Create a kind of ModuleLoader for one module
# The parameters are:
# * parent_loader - typically the loader for the root
# * module_name - the name of the module (non qualified name)
# * gem_ref - [URI, String] gem reference to the root of the module (URI, gem://gemname/optional/path/in/gem), or
# just the gem's name as a String.
#
def initialize(parent_loader, loaders, module_name, gem_ref, loader_name, loadables = LOADABLE_KINDS)
@gem_ref = gem_ref
super parent_loader, loaders, module_name, gem_dir(gem_ref), loader_name, loadables
end
def to_s
"(ModuleLoader::GemBased '#{loader_name}' '#{@gem_ref}' [#{module_name}])"
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/loader/generic_plan_instantiator.rb | lib/puppet/pops/loader/generic_plan_instantiator.rb | # frozen_string_literal: true
module Puppet::Pops
module Loader
# The GenericPlanInstantiator dispatches to either PuppetPlanInstantiator or a
# yaml_plan_instantiator injected through the Puppet context, depending on
# the type of the plan.
#
class GenericPlanInstantiator
def self.create(loader, typed_name, source_refs)
if source_refs.length > 1
raise ArgumentError, _("Found multiple files for plan '%{plan_name}' but only one is allowed") % { plan_name: typed_name.name }
end
source_ref = source_refs[0]
code_string = Puppet::FileSystem.read(source_ref, :encoding => 'utf-8')
instantiator = if source_ref.end_with?('.pp')
Puppet::Pops::Loader::PuppetPlanInstantiator
else
Puppet.lookup(:yaml_plan_instantiator) do
raise Puppet::DevError, _("No instantiator is available to load plan from %{source_ref}") % { source_ref: source_ref }
end
end
instantiator.create(loader, typed_name, source_ref, code_string)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/loader/ruby_data_type_instantiator.rb | lib/puppet/pops/loader/ruby_data_type_instantiator.rb | # frozen_string_literal: true
# The RubyTypeInstantiator instantiates a data type from the ruby source
# that calls Puppet::DataTypes.create_type.
#
class Puppet::Pops::Loader::RubyDataTypeInstantiator
# Produces an instance of class derived from PAnyType 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 type is associated with
# @param typed_name [Puppet::Pops::Loader::TypedName] the type / name of the type 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::Types::PAnyType] - an instantiated data type 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::DataTypes\.create_type/
raise ArgumentError, _("The code loaded from %{source_ref} does not seem to be a Puppet 5x API data type - no create_type call.") % { source_ref: source_ref }
end
# make the private loader available in a binding to allow it to be passed on
loader_for_type = loader.private_loader
here = get_binding(loader_for_type)
created = eval(ruby_code_string, here, source_ref, 1) # rubocop:disable Security/Eval
unless created.is_a?(Puppet::Pops::Types::PAnyType)
raise ArgumentError, _("The code loaded from %{source_ref} did not produce a data type when evaluated. Got '%{klass}'") % { source_ref: source_ref, klass: created.class }
end
unless created.name.casecmp(typed_name.name) == 0
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
created
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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/loader/puppet_resource_type_impl_instantiator.rb | lib/puppet/pops/loader/puppet_resource_type_impl_instantiator.rb | # frozen_string_literal: true
module Puppet::Pops
module Loader
# The PuppetResourceTypeImplInstantiator instantiates a Puppet::Pops::ResourceTypeImpl object.
# given a Puppet Programming language source that when called evaluates the Puppet logic it contains.
#
class PuppetResourceTypeImplInstantiator
# Produces an instance of Puppet::Pops::ResourceTypeImpl, or fails with an error if the
# given puppet source does not produce such an instance when evaluated.
#
# @param loader [Loader] The loader the function is associated with
# @param typed_name [TypedName] the type / name of the resource type impl to load
# @param source_ref [URI, String] a reference to the source / origin of the puppet code to evaluate
# @param pp_code_string [String] puppet code in a string
#
# @return [Puppet::Pops::ResourceTypeImpl] - an instantiated ResourceTypeImpl
#
def self.create(loader, typed_name, source_ref, pp_code_string)
parser = Parser::EvaluatingParser.new()
# parse and validate
model = parser.parse_string(pp_code_string, source_ref)
statements = if model.is_a?(Model::Program)
if model.body.is_a?(Model::BlockExpression)
model.body.statements
else
[model.body]
end
else
EMPTY_ARRAY
end
statements = statements.reject { |s| s.is_a?(Model::Nop) }
if statements.empty?
raise ArgumentError, _("The code loaded from %{source_ref} does not create the resource type '%{type_name}' - it is empty") % { source_ref: source_ref, type_name: typed_name.name }
end
rname = Resource::ResourceTypeImpl._pcore_type.name
unless statements.find do |s|
if s.is_a?(Model::CallMethodExpression)
functor_expr = s.functor_expr
functor_expr.is_a?(Model::NamedAccessExpression) &&
functor_expr.left_expr.is_a?(Model::QualifiedReference) &&
functor_expr.left_expr.cased_value == rname &&
functor_expr.right_expr.is_a?(Model::QualifiedName) &&
functor_expr.right_expr.value == 'new'
else
false
end
end
raise ArgumentError, _("The code loaded from %{source_ref} does not create the resource type '%{type_name}' - no call to %{rname}.new found.") % { source_ref: source_ref, type_name: typed_name.name, rname: rname }
end
unless statements.size == 1
raise ArgumentError, _("The code loaded from %{source_ref} must contain only the creation of resource type '%{type_name}' - it has additional logic.") % { source_ref: source_ref, type_name: typed_name.name }
end
closure_scope = Puppet.lookup(:global_scope) { {} }
resource_type_impl = parser.evaluate(closure_scope, model)
unless resource_type_impl.is_a?(Puppet::Pops::Resource::ResourceTypeImpl)
got = resource_type.class
raise ArgumentError, _("The code loaded from %{source_ref} does not define the resource type '%{type_name}' - got '%{got}'.") % { source_ref: source_ref, type_name: typed_name.name, got: got }
end
unless resource_type_impl.name == typed_name.name
expected = typed_name.name
actual = resource_type_impl.name
raise ArgumentError, _("The code loaded from %{source_ref} produced resource type with the wrong name, expected '%{expected}', actual '%{actual}'") % { source_ref: source_ref, expected: expected, actual: actual }
end
# Adapt the resource type definition with loader - this is used from logic contained in it body to find the
# loader to use when making calls to the new function API. Such logic have a hard time finding the closure (where
# the loader is known - hence this mechanism
Adapters::LoaderAdapter.adapt(resource_type_impl).loader_name = loader.loader_name
resource_type_impl
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/loader/loader.rb | lib/puppet/pops/loader/loader.rb | # frozen_string_literal: true
# Loader
# ===
# A Loader is responsible for loading "entities" ("instantiable and executable objects in the puppet language" which
# are type, hostclass, definition, function, and bindings.
#
# The main method for users of a Loader is the `load` or `load_typed methods`, which returns a previously loaded entity
# of a given type/name, and searches and loads the entity if not already loaded.
#
# private entities
# ---
# TODO: handle loading of entities that are private. Suggest that all calls pass an origin_loader (the loader
# where request originated (or symbol :public). A module loader has one (or possibly a list) of what is
# considered to represent private loader - i.e. the dependency loader for a module. If an entity is private
# it should be stored with this status, and an error should be raised if the origin_loader is not on the list
# of accepted "private" loaders.
# The private loaders can not be given at creation time (they are parented by the loader in question). Another
# alternative is to check if the origin_loader is a child loader, but this requires bidirectional links
# between loaders or a search if loader with private entity is a parent of the origin_loader).
#
# @api public
#
module Puppet::Pops
module Loader
ENVIRONMENT = 'environment'
ENVIRONMENT_PRIVATE = 'environment private'
class Loader
attr_reader :environment, :loader_name
# Describes the kinds of things that loaders can load
LOADABLE_KINDS = [:func_4x, :func_4xpp, :func_3x, :datatype, :type_pp, :resource_type_pp, :plan, :task].freeze
# @param [String] name the name of the loader. Must be unique among all loaders maintained by a {Loader} instance
def initialize(loader_name, environment)
@loader_name = loader_name.freeze
@environment = environment
end
# Search all places where this loader would find values of a given type and return a list the
# found values for which the given block returns true. All found entries will be returned if no
# block is given.
#
# Errors that occur function discovery will either be logged as warnings or collected by the optional
# `error_collector` array. When provided, it will receive {Puppet::DataTypes::Error} instances describing
# each error in detail and no warnings will be logged.
#
# @param type [Symbol] the type of values to search for
# @param error_collector [Array<Puppet::DataTypes::Error>] an optional array that will receive errors during load
# @param name_authority [String] the name authority, defaults to the pcore runtime
# @yield [typed_name] optional block to filter the results
# @yieldparam [TypedName] typed_name the typed name of a found entry
# @yieldreturn [Boolean] `true` to keep the entry, `false` to discard it.
# @return [Array<TypedName>] the list of names of discovered values
def discover(type, error_collector = nil, name_authority = Pcore::RUNTIME_NAME_AUTHORITY, &block)
EMPTY_ARRAY
end
# Produces the value associated with the given name if already loaded, or available for loading
# by this loader, one of its parents, or other loaders visible to this loader.
# This is the method an external party should use to "get" the named element.
#
# An implementor of this method should first check if the given name is already loaded by self, or a parent
# loader, and if so return that result. If not, it should call `find` to perform the loading.
#
# @param type [:Symbol] the type to load
# @param name [String, Symbol] the name of the entity to load
# @return [Object, nil] the value or nil if not found
#
# @api public
#
def load(type, name)
synchronize do
result = load_typed(TypedName.new(type, name.to_s))
if result
result.value
end
end
end
# Loads the given typed name, and returns a NamedEntry if found, else returns nil.
# This the same a `load`, but returns a NamedEntry with origin/value information.
#
# @param typed_name [TypedName] - the type, name combination to lookup
# @return [NamedEntry, nil] the entry containing the loaded value, or nil if not found
#
# @api public
#
def load_typed(typed_name)
raise NotImplementedError, "Class #{self.class.name} must implement method #load_typed"
end
# Returns an already loaded entry if one exists, or nil. This does not trigger loading
# of the given type/name.
#
# @param typed_name [TypedName] - the type, name combination to lookup
# @param check_dependencies [Boolean] - if dependencies should be checked in addition to here and parent
# @return [NamedEntry, nil] the entry containing the loaded value, or nil if not found
# @api public
#
def loaded_entry(typed_name, check_dependencies = false)
raise NotImplementedError, "Class #{self.class.name} must implement method #loaded_entry"
end
# Produces the value associated with the given name if defined **in this loader**, or nil if not defined.
# This lookup does not trigger any loading, or search of the given name.
# An implementor of this method may not search or look up in any other loader, and it may not
# define the name.
#
# @param typed_name [TypedName] - the type, name combination to lookup
#
# @api private
#
def [](typed_name)
found = get_entry(typed_name)
if found
found.value
else
nil
end
end
# Searches for the given name in this loader's context (parents should already have searched their context(s) without
# producing a result when this method is called).
# An implementation of find typically caches the result.
#
# @param typed_name [TypedName] the type, name combination to lookup
# @return [NamedEntry, nil] the entry for the loaded entry, or nil if not found
#
# @api private
#
def find(typed_name)
raise NotImplementedError, "Class #{self.class.name} must implement method #find"
end
# Returns the parent of the loader, or nil, if this is the top most loader. This implementation returns nil.
def parent
nil
end
# Produces the private loader for loaders that have a one (the visibility given to loaded entities).
# For loaders that does not provide a private loader, self is returned.
#
# @api private
def private_loader
self
end
# Lock around a block
# This exists so some subclasses that are set up statically and don't actually
# load can override it
def synchronize(&block)
@environment.lock.synchronize(&block)
end
# Binds a value to a name. The name should not start with '::', but may contain multiple segments.
#
# @param type [:Symbol] the type of the entity being set
# @param name [String, Symbol] the name of the entity being set
# @param origin [URI, #uri, String] the origin of the set entity, a URI, or provider of URI, or URI in string form
# @return [NamedEntry, nil] the created entry
#
# @api private
#
def set_entry(type, name, value, origin = nil)
raise NotImplementedError
end
# Produces a NamedEntry if a value is bound to the given name, or nil if nothing is bound.
#
# @param typed_name [TypedName] the type, name combination to lookup
# @return [NamedEntry, nil] the value bound in an entry
#
# @api private
#
def get_entry(typed_name)
raise NotImplementedError
end
# A loader is by default a loader for all kinds of loadables. An implementation may override
# if it cannot load all kinds.
#
# @api private
def loadables
LOADABLE_KINDS
end
# A loader may want to implement its own version with more detailed information.
def to_s
loader_name
end
# Loaders may contain references to the environment they load items within.
# Consequently, calling Kernel#inspect may return strings that are large
# enough to cause OutOfMemoryErrors on some platforms.
#
# We do not call alias_method here as that would copy the content of to_s
# at this point to inspect (ie children would print out `loader_name`
# rather than their version of to_s if they chose to implement it).
def inspect
to_s
end
# An entry for one entity loaded by the loader.
#
class NamedEntry
attr_reader :typed_name
attr_reader :value
attr_reader :origin
def initialize(typed_name, value, origin)
@typed_name = typed_name
@value = value
@origin = origin
freeze()
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/loader/simple_environment_loader.rb | lib/puppet/pops/loader/simple_environment_loader.rb | # frozen_string_literal: true
# SimpleEnvironmentLoader
# ===
# This loader does not load anything and it is populated by the bootstrapping logic that loads
# the site.pp or equivalent for an environment. It does not restrict the names of what it may contain,
# and what is loaded here overrides any child loaders (modules).
#
class Puppet::Pops::Loader::SimpleEnvironmentLoader < Puppet::Pops::Loader::BaseLoader
attr_accessor :private_loader
# Never finds anything, everything "loaded" is set externally
def find(typed_name)
nil
end
def to_s
"(SimpleEnvironmentLoader '#{loader_name}')"
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/loader/task_instantiator.rb | lib/puppet/pops/loader/task_instantiator.rb | # frozen_string_literal: true
# The TypeDefinitionInstantiator instantiates a type alias or a type definition
#
require_relative '../../../puppet/module/task'
module Puppet::Pops
module Loader
class TaskInstantiator
def self.create(loader, typed_name, source_refs)
name = typed_name.name
basename = typed_name.name_parts[1] || 'init'
dirname = File.dirname(source_refs[0])
metadata_files, executables = source_refs.partition { |source_ref| source_ref.end_with?('.json') }
metadata_file = metadata_files.find { |source_ref| File.basename(source_ref, '.json') == basename }
metadata = Puppet::Module::Task.read_metadata(metadata_file) || {}
files = Puppet::Module::Task.find_files(name, dirname, metadata, executables)
task = { 'name' => name, 'metadata' => metadata, 'files' => files }
begin
unless metadata['parameters'].is_a?(Hash) || metadata['parameters'].nil?
msg = _('Failed to load metadata for task %{name}: \'parameters\' must be a hash') % { name: name }
raise Puppet::ParseError.new(msg, metadata_file)
end
task['parameters'] = convert_types(metadata['parameters'])
Types::TypeFactory.task.from_hash(task)
rescue Types::TypeAssertionError => ex
# Not strictly a parser error but from the users perspective, the file content didn't parse properly. The
# ParserError also conveys file info (even though line is unknown)
msg = _('Failed to load metadata for task %{name}: %{reason}') % { name: name, reason: ex.message }
raise Puppet::ParseError.new(msg, metadata_file)
end
end
def self.convert_types(args)
args.transform_values do |v|
v['type'].nil? ? Types::TypeFactory.data : Types::TypeParser.singleton.parse(v['type'])
end if args
end
private_class_method :convert_types
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/loader/loader_paths.rb | lib/puppet/pops/loader/loader_paths.rb | # frozen_string_literal: true
# LoaderPaths
# ===
# The central loader knowledge about paths, what they represent and how to instantiate from them.
# Contains helpers (*smart paths*) to deal with lazy resolution of paths.
#
# TODO: Currently only supports loading of functions (2 kinds)
#
module Puppet::Pops
module Loader
module LoaderPaths
# Returns an array of SmartPath, each instantiated with a reference to the given loader (for root path resolution
# and existence checks). The smart paths in the array appear in precedence order. The returned array may be
# mutated.
#
def self.relative_paths_for_type(type, loader)
result = []
case type
when :function
# Only include support for the loadable items the loader states it can contain
if loader.loadables.include?(:func_4x)
result << FunctionPath4x.new(loader)
end
if loader.loadables.include?(:func_4xpp)
result << FunctionPathPP.new(loader)
end
if loader.loadables.include?(:func_3x)
result << FunctionPath3x.new(loader)
end
when :plan
result << PlanPath.new(loader)
when :task
result << TaskPath.new(loader) if Puppet[:tasks] && loader.loadables.include?(:task)
when :type
result << DataTypePath.new(loader) if loader.loadables.include?(:datatype)
result << TypePathPP.new(loader) if loader.loadables.include?(:type_pp)
when :resource_type_pp
result << ResourceTypeImplPP.new(loader) if loader.loadables.include?(:resource_type_pp)
else
# unknown types, simply produce an empty result; no paths to check, nothing to find... move along...
[]
end
result
end
# # DO NOT REMOVE YET. needed later? when there is the need to decamel a classname
# def 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
class SmartPath
# Creates SmartPath for the given loader (loader knows how to check for existence etc.)
def initialize(loader)
@loader = loader
end
# Generic path, in the sense of "if there are any entities of this kind to load, where are they?"
def generic_path
return @generic_path unless @generic_path.nil?
the_root_path = root_path # @loader.path
@generic_path = (the_root_path.nil? ? relative_path : File.join(the_root_path, relative_path))
end
def fuzzy_matching?
false
end
def root_path
@loader.path
end
def lib_root?
@loader.lib_root?
end
# Effective path is the generic path + the name part(s) + extension.
#
def effective_path(typed_name, start_index_in_name)
"#{File.join(generic_path, typed_name.name_parts)}#{extension}"
end
def typed_name(type, name_authority, relative_path, module_name)
# Module name is assumed to be included in the path and therefore not added here
n = ''.dup
unless extension.empty?
# Remove extension
relative_path = relative_path[0..-(extension.length + 1)]
end
relative_path.split('/').each do |segment|
n << '::' if n.size > 0
n << segment
end
TypedName.new(type, n, name_authority)
end
def valid_path?(path)
path.end_with?(extension) && path.start_with?(generic_path)
end
def valid_name?(typed_name)
true
end
def relative_path
raise NotImplementedError
end
def instantiator
raise NotImplementedError
end
end
class RubySmartPath < SmartPath
EXTENSION = '.rb'
def extension
EXTENSION
end
# Duplication of extension information, but avoids one call
def effective_path(typed_name, start_index_in_name)
"#{File.join(generic_path, typed_name.name_parts)}.rb"
end
end
# A PuppetSmartPath is rooted at the loader's directory one level up from what the loader specifies as it
# path (which is a reference to its 'lib' directory.
#
class PuppetSmartPath < SmartPath
EXTENSION = '.pp'
def extension
EXTENSION
end
# Duplication of extension information, but avoids one call
def effective_path(typed_name, start_index_in_name)
# Puppet name to path always skips the name-space as that is part of the generic path
# i.e. <module>/mymodule/functions/foo.pp is the function mymodule::foo
parts = typed_name.name_parts
if start_index_in_name > 0
return nil if start_index_in_name >= parts.size
parts = parts[start_index_in_name..]
end
"#{File.join(generic_path, parts)}#{extension}"
end
def typed_name(type, name_authority, relative_path, module_name)
n = ''.dup
n << module_name unless module_name.nil?
unless extension.empty?
# Remove extension
relative_path = relative_path[0..-(extension.length + 1)]
end
relative_path.split('/').each do |segment|
n << '::' if n.size > 0
n << segment
end
TypedName.new(type, n, name_authority)
end
end
class FunctionPath4x < RubySmartPath
SYSTEM_FUNCTION_PATH_4X = File.join('puppet', 'functions').freeze
FUNCTION_PATH_4X = File.join('lib', SYSTEM_FUNCTION_PATH_4X).freeze
def relative_path
lib_root? ? SYSTEM_FUNCTION_PATH_4X : FUNCTION_PATH_4X
end
def instantiator
RubyFunctionInstantiator
end
end
class FunctionPath3x < RubySmartPath
SYSTEM_FUNCTION_PATH_3X = File.join('puppet', 'parser', 'functions').freeze
FUNCTION_PATH_3X = File.join('lib', SYSTEM_FUNCTION_PATH_3X).freeze
def relative_path
lib_root? ? SYSTEM_FUNCTION_PATH_3X : FUNCTION_PATH_3X
end
def instantiator
RubyLegacyFunctionInstantiator
end
end
class FunctionPathPP < PuppetSmartPath
FUNCTION_PATH_PP = 'functions'
def relative_path
FUNCTION_PATH_PP
end
def instantiator
PuppetFunctionInstantiator
end
end
class DataTypePath < RubySmartPath
SYSTEM_TYPE_PATH = File.join('puppet', 'datatypes').freeze
TYPE_PATH = File.join('lib', SYSTEM_TYPE_PATH).freeze
def relative_path
lib_root? ? SYSTEM_TYPE_PATH : TYPE_PATH
end
def instantiator
RubyDataTypeInstantiator
end
end
class TypePathPP < PuppetSmartPath
TYPE_PATH_PP = 'types'
def relative_path
TYPE_PATH_PP
end
def instantiator
TypeDefinitionInstantiator
end
end
# TaskPath is like PuppetSmartPath but it does not use an extension and may
# match more than one path with one name
class TaskPath < PuppetSmartPath
TASKS_PATH = 'tasks'
FORBIDDEN_EXTENSIONS = %w[.conf .md].freeze
def extension
EMPTY_STRING
end
def fuzzy_matching?
true
end
def relative_path
TASKS_PATH
end
def typed_name(type, name_authority, relative_path, module_name)
n = ''.dup
n << module_name unless module_name.nil?
# Remove the file extension, defined as everything after the *last* dot.
relative_path = relative_path.sub(%r{\.[^/.]*\z}, '')
if relative_path == 'init' && !(module_name.nil? || module_name.empty?)
TypedName.new(type, module_name, name_authority)
else
relative_path.split('/').each do |segment|
n << '::' if n.size > 0
n << segment
end
TypedName.new(type, n, name_authority)
end
end
def instantiator
require_relative 'task_instantiator'
TaskInstantiator
end
def valid_name?(typed_name)
# TODO: Remove when PE has proper namespace handling
typed_name.name_parts.size <= 2
end
def valid_path?(path)
path.start_with?(generic_path) && is_task_name?(File.basename(path, '.*')) && !FORBIDDEN_EXTENSIONS.any? { |ext| path.end_with?(ext) }
end
def is_task_name?(name)
!!(name =~ /^[a-z][a-z0-9_]*$/)
end
end
class ResourceTypeImplPP < PuppetSmartPath
RESOURCE_TYPES_PATH_PP = '.resource_types'
def relative_path
RESOURCE_TYPES_PATH_PP
end
def root_path
@loader.path
end
def instantiator
PuppetResourceTypeImplInstantiator
end
# The effect paths for resource type impl is the full name
# since resource types are not name spaced.
# This overrides the default PuppetSmartPath.
#
def effective_path(typed_name, start_index_in_name)
# Resource type to name does not skip the name-space
# i.e. <module>/mymodule/resource_types/foo.pp is the resource type foo
"#{File.join(generic_path, typed_name.name_parts)}.pp"
end
end
class PlanPath < PuppetSmartPath
PLAN_PATH = File.join('plans')
PP_EXT = '.pp'
YAML_EXT = '.yaml'
def initialize(loader)
super
if Puppet.lookup(:yaml_plan_instantiator) { nil }
@extensions = [PP_EXT, YAML_EXT]
else
@extensions = [PP_EXT]
end
@init_filenames = @extensions.map { |ext| "init#{ext}" }
end
def extension
EMPTY_STRING
end
def relative_path
PLAN_PATH
end
def instantiator
Puppet::Pops::Loader::GenericPlanInstantiator
end
def fuzzy_matching?
true
end
def valid_path?(path)
@extensions.any? { |ext| path.end_with?(ext) } && path.start_with?(generic_path)
end
def typed_name(type, name_authority, relative_path, module_name)
if @init_filenames.include?(relative_path) && !(module_name.nil? || module_name.empty?)
TypedName.new(type, module_name, name_authority)
else
n = ''.dup
n << module_name unless module_name.nil?
ext = @extensions.find { |extension| relative_path.end_with?(extension) }
relative_path = relative_path[0..-(ext.length + 1)]
relative_path.split('/').each do |segment|
n << '::' if n.size > 0
n << segment
end
TypedName.new(type, n, name_authority)
end
end
def effective_path(typed_name, start_index_in_name)
# Puppet name to path always skips the name-space as that is part of the generic path
# i.e. <module>/mymodule/functions/foo.pp is the function mymodule::foo
parts = typed_name.name_parts
if start_index_in_name > 0
return nil if start_index_in_name >= parts.size
parts = parts[start_index_in_name..]
end
basename = File.join(generic_path, parts)
@extensions.map { |ext| "#{basename}#{ext}" }
end
end
# SmartPaths
# ===
# Holds effective SmartPath instances per type
#
class SmartPaths
def initialize(path_based_loader)
@loader = path_based_loader
@smart_paths = {}
end
# Ensures that the paths for the type have been probed and pruned to what is existing relative to
# the given root.
#
# @param type [Symbol] the entity type to load
# @return [Array<SmartPath>] array of effective paths for type (may be empty)
#
def effective_paths(type)
smart_paths = @smart_paths
loader = @loader
effective_paths = smart_paths[type]
unless effective_paths
# type not yet processed, does the various directories for the type exist ?
# Get the relative dirs for the type
paths_for_type = LoaderPaths.relative_paths_for_type(type, loader)
# Check which directories exist in the loader's content/index
effective_paths = smart_paths[type] = paths_for_type.select { |sp| loader.meaningful_to_search?(sp) }
end
effective_paths
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/loader/gem_support.rb | lib/puppet/pops/loader/gem_support.rb | # frozen_string_literal: true
# GemSupport offers methods to find a gem's location by name or gem://gemname URI.
#
# TODO: The Puppet 3x, uses Puppet::Util::RubyGems to do this, and obtain paths, and avoids using ::Gems
# when ::Bundler is in effect. A quick check what happens on Ruby 1.8.7 and Ruby 1.9.3 with current
# version of bundler seems to work just fine without jumping through any hoops. Hopefully the Puppet::Utils::RubyGems is
# just dealing with arcane things prior to RubyGems 1.8 that are not needed any more. To verify there is
# the need to set up a scenario where additional bundles than what Bundler allows for a given configuration are available
# and then trying to access those.
#
module Puppet::Pops::Loader::GemSupport
# Produces the root directory of a gem given as an URI (gem://gemname/optional/path), or just the
# gemname as a string.
#
def gem_dir(uri_or_string)
case uri_or_string
when URI
gem_dir_from_uri(uri_or_string)
when String
gem_dir_from_name(uri_or_string)
end
end
# Produces the root directory of a gem given as an uri, where hostname is the gemname, and an optional
# path is appended to the root of the gem (i.e. if the reference is given to a sub-location within a gem.
# TODO: FIND by name raises exception Gem::LoadError with list of all gems on the path
#
def gem_dir_from_uri(uri)
spec = Gem::Specification.find_by_name(uri.hostname)
unless spec
raise ArgumentError, _("Gem not found %{uri}") % { uri: uri }
end
# if path given append that, else append given subdir
if uri.path.empty?
spec.gem_dir
else
File.join(spec.full_gem_path, uri.path)
end
end
# Produces the root directory of a gem given as a string with the gem's name.
# TODO: FIND by name raises exception Gem::LoadError with list of all gems on the path
#
def gem_dir_from_name(gem_name)
spec = Gem::Specification.find_by_name(gem_name)
unless spec
raise ArgumentError, _("Gem not found '%{gem_name}'") % { gem_name: gem_name }
end
spec.full_gem_path
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.