# frozen-string-literal: true
#
# Copyright (C) 2019 Thomas Baron
#
# This file is part of term_utils.
#
# term_utils is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# term_utils is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with term_utils. If not, see .
module TermUtils
module AP
# Represents the argument list syntax. It holds a list of parameters and
# levels.
class Syntax
# @return [Array]
attr_accessor :elements
# Constructs a new Syntax.
def initialize
@elements = []
end
# For dup method.
def initialize_dup(other)
if other.elements
@elements = []
other.elements.each do |e|
@elements << e.dup
end
end
super
end
# Finalizes this one. Internal use.
# @return [nil]
def finalize!(opts = {})
opts[:anonymous] = 0 unless opts.has_key? :anonymous
@elements.each { |e| e.finalize!(opts) }
end
# Creates and adds a new Parameter.
# @param opts [Hash]
# @option opts [Symbol] :id
# @option opts [Integer] :min_occurs Default value is `0`.
# @option opts [Integer] :max_occurs Default value is `1`.
# @return [TermUtils::AP::Parameter]
def define_parameter(opts = {}, &block)
new_parameter = TermUtils::AP::Parameter.new(opts)
@elements << new_parameter
block.call(new_parameter) if block
new_parameter
end
# Creates and adds a new Level.
# @param opts [Hash]
# @option opts [Symbol] :id
# @option opts [Integer] :min_occurs Default value is `0`.
# @option opts [Integer] :max_occurs Default value is `1`.
# @return [TermUtils::AP::Level]
def define_level(opts = {}, &block)
new_level = TermUtils::AP::Level.new(opts)
@elements << new_level
block.call(new_level) if block
new_level
end
# Fetches all direct flagged parameters and levels.
# @return [Array]
# @see TermUtils::AP::Syntax#fetch_flagged_elements
# @see TermUtils::AP::Syntax#fetch_unflagged_parameters
def fetch_elements
flagged_elems = {}
unflagged_params = []
@elements.each do |e|
if e.flags.empty?
# Parameter
unflagged_params << e
else
# Parameter or Level
e.flags.each do |f|
flagged_elems[f.to_s] = e
end
end
end
[flagged_elems, unflagged_params]
end
# Fetches all direct flagged parameters and levels.
# @return [Hash]
def fetch_flagged_elements
elems = {}
@elements.each do |e|
e.flags.each do |f|
elems[f.to_s] = e
end
end
elems
end
# Fetches all direct unflagged.
# @return [Array]
def fetch_unflagged_parameters
params = []
@elements.each do |e|
next unless e.is_a? TermUtils::AP::Parameter
params << e if e.flags.empty?
end
params
end
end
end
end