# Author:: Ruben Heradio Gil (mailto:rheradio@lsi.uned.es)

#Auxiliar AspectGen class that represents a Pointcut
class Pointcut < Regexp 
	#Pointcut name (a String)
	attr_accessor :name
	#Pointcut value (a Regexp)
	attr_accessor :regExp
	#Pointcut scope ('local' or 'global')
	attr_accessor :scope
	
	# * 'name' = Pointcut name (a String)
	# * 'regExp' = Pointcut value (a Regexp)
	# * 'scope' = Pointcut scope ('local' or 'global')
	def constructor(name, regExp, scope='local')
		raise "First argument of Pointcut constructor must be a String" if !name.kind_of?(String)
		raise "Second argument of Pointcut constructor must be a Regular Expression" if !regExp.kind_of?(Regexp)
		raise "Pointcut scope must be 'local' or 'global'" if (scope != 'local') and 
			(scope != 'global')
		super(regExp)
		@name = name
		@regExp = regExp
		@scope = scope
	end #constructor
	
	def clone
		result = Pointcut.new(@name.clone, @regExp.clone, @scope.clone)
	end #clone
	
	#Determine if two Pointcuts ('self' and 'pointcut') applied over the same input file ('fin') go crash
	def crash?(pointcut, fin)

		raise "First argument of Pointcut#crash? must be a Pointcut" if !pointcut.kind_of?(Pointcut)
		# crash? inner auxiliar method that determines if two local Pointcuts ('pointcut1' and 'pointcut2') applied over the String tr' go crash
		def crashAux1?(pointcut1, pointcut2, str)
			position1 = str =~ pointcut1
			match1 = $&
			position2 = str =~ pointcut2
			match2 = $&
			return false if (position1 == nil) or (position2 == nil)
			if (position1 <= position2) 
				return true if (position1 + match1.length - 1) >= position2
			else
				return true if (position2 + match2.length - 1) >= position1
			end #if
			return false
		end #crashAux1?

		# crash? inner auxiliar method that determines if a global Pointcut ('globalPointcut') and a local
		# Pointcut ('localPointcut') applied over the String tr' go crash
		def crashAux2?(globalPointcut, localPointcut, str)
			crash = false
			while (str.index(globalPointcut) != nil) and (crash == false)
				crash = crashAux1?(globalPointcut, localPointcut, str)
				str =~ globalPointcut
				str = $'
			end #while
			return crash
		end
		
		crash = false
		File.open(fin) { |f|
			fcode = f.read
			if (self.scope == 'local') and (pointcut.scope == 'local')
				crash = crashAux1?(self, pointcut, fcode)
			elsif (self.scope == 'local') and (pointcut.scope == 'global')
				crash = crashAux2?(pointcut, self, fcode)
			elsif (self.scope == 'global') and (pointcut.scope == 'local')
				crash = crashAux2?(self, pointcut, fcode)
			else #if (self.scope == 'global') and (pointcut.scope == 'global')
				crash = ( crashAux2?(self, pointcut, fcode) or				
					      crashAux2?(pointcut, self, fcode) )
			end #if
		}
		return crash
	end #crash?

end #Pointcut

#Auxiliar AspectGen class that represents an Advice
class Advice
	#Advice name (a String)
	attr_accessor :name
	#Name of the Pointcut associated with the Advice (a String)
	attr_accessor :pointcut
	#Advice value. String that will replace the text matched by the Pointcut value
	attr_accessor :subText

	# * 'name' = Advice name (a String)
	# * 'pointcut' = Name of the Pointcut associated with the Advice (a String)
	# * 'subtext' = Advice value. String that will replace the text matched by the Pointcut value
	def constructor(name, pointcut, subText)
	
		raise "Arguments of Advice constructor must be a String" if (!name.kind_of?(String)) or
			(!pointcut.kind_of?(String)) or (!subText.kind_of?(String)) 
		@name = name
		@pointcut = pointcut
		@subText = subText
	end #constructor
	
	def clone
		result = Advice.new(@name.clone, @pointcut.clone, @subText.clone)
	end #clone

end #Advice

#Auxiliar AspectGen class that represents a Generation
class Generation
	#Generation name (a String)
	attr_accessor :name
	#Generation sterotype file (a String)
	attr_accessor :fin
	#Generation output file (a String)
	attr_accessor :fout
	#List of Advice names associated with the Generation (a String List)
	attr_accessor :adviceList
	
	# * 'name' = Generation name (a String)
	# * 'fin' = Generation sterotype file (a String)
	# * 'fout' = Generation output file (a String)
	# * 'adviceList' = List of Advice names associated with the Generation (a String List)
	def constructor(name, fin, fout, adviceList = [])
		raise "First argument of Generation constructor must be a String" if !name.kind_of?(String)
		raise "Fourth argument of Generation constructor must be a String List" if !adviceList.kind_of?(Array)
		adviceList.each { |a|
			raise "Fourth argument of Generation constructor must be a String List" if !a.kind_of?(String)
		} #adviceList.each
		@name = name
		@fin = fin
		@fout = fout
		@adviceList = adviceList
	end #constructor

	def clone
		result = Generation.new(@name, @fin, @fout, @adviceList.clone)
	end #clone
	
end #Generation

class AspectGen

	# Counter used by cloneSuffix
	@@suffixes = 0

	# Protected Binding object that describes the variable and method bindings at the point of constructor call
	attr_accessor :args
	# Protected hash table that stores the Pointcuts of 'self'
	attr_accessor :pointcutHash
	# Protected hash table that stores the Advices of 'self'
	attr_accessor :adviceHash
	# Protected hash table that stores the Generations of 'self'
	attr_accessor :generationHash
	
	#@pointcutHash = {}
	@adviceHash = {}
	@generationHash = {}
	
	#Esto habra que verlo
	protected :pointcutHash, :adviceHash, :generationHash

	def clone
		result = AspectGen.new(@args)
		result.pointcutHash = @pointcutHash.clone
		result.adviceHash = @adviceHash.clone
		result.generationHash = @generationHash.clone
		return result
	end #clone
	
	# + auxiliar method that produces a clone where all elements (Pointcuts, Advices and Generations) have been added
	# a numerical suffix (@@suffixes is a private class attribute that will be incremented everytime method '+' is
	# called).
	# For example, if @suffixes value is 8, then
	# 
	# pointcut('p1', /expReg/, 'global') -> pointcut('p1_8', /expReg/, 'global')
	def cloneSuffix
		result = self.clone
		@generationHash.each { |k, g|
				result.generationHash[k + '_' + @@suffixes.to_s] =
					@generationHash[k]
				result.generationHash[k + '_' + @@suffixes.to_s].name +=
					'_' + @@suffixes.to_s
				result.generationHash[k + '_' + @@suffixes.to_s].adviceList.collect! { |e|
					e + '_' + @@suffixes.to_s
				} #collect	
				result.generationHash.delete(k)				
		} #@generationHash.each
		@adviceHash.each { |k, g|
				result.adviceHash[k + '_' + @@suffixes.to_s] = 
					@adviceHash[k]
				result.adviceHash[k + '_' + @@suffixes.to_s].name +=
					'_' + @@suffixes.to_s
				result.adviceHash[k + '_' + @@suffixes.to_s].pointcut += 
					'_' + @@suffixes.to_s
				result.adviceHash.delete(k)				
		} #@generationHash.each
		@pointcutHash.each { |k, g|
				result.pointcutHash[k + '_' + @@suffixes.to_s] = 
					@pointcutHash[k]
				result.pointcutHash[k + '_' + @@suffixes.to_s].name +=
					'_' + @@suffixes.to_s
				result.pointcutHash.delete(k)				
		} #@generationHash.each		
		@@suffixes += 1
		return result
	end #cloneSuffix

	# Adds a new Pointcut to 'self'
	# * 'name' = Pointcut name (a String)
	# * 'regExp' = Pointcut value (a Regexp)
	# * 'scope' = Pointcut scope ('local' or 'global')
	def pointcut(name, regExp, scope = 'local')
		@pointcutHash = {} unless @pointcutHash
		@pointcutHash[name] = Pointcut.new(name, regExp, scope)
	 end #pointcut
	 
	# Adds a new Advice to 'self'
	# * 'name' = Advice name (a String)
	# * 'pointcut' = Name of the Pointcut associated with the Advice (a String)
	# * 'subtext' = Advice value. String that will replace the text matched by the Pointcut value
	 def advice(name, pointcut, subText)
		raise "Pointcut referenced by AspectGen#advice doesn't exist" if pointcutHash[pointcut] == nil
		@adviceHash = {} unless @adviceHash
	 	@adviceHash[name] = Advice.new(name, pointcut, subText)
	 end #advice

	# Adds a new Generation to 'self'
	# * 'name' = Generation name (a String)
	# * 'fin' = Generation sterotype file (a String)
	# * 'fout' = Generation output file (a String)
	# * 'adviceList' = List of Advice names associated with the Generation (a String List)
	 def generation(name, fin, fout, adviceList = [])
		@generationHash = {} unless @generationHash
		
		raise "Fourth argument of Generation constructor must be a String List" if !adviceList.kind_of?(Array)
		adviceList.each { |a|
			raise "Advice referenced by AspectGen#generation doesn't exist" if adviceHash[a] == nil
		} #adviceList.each
		adviceListAux = adviceList
		adviceList.each { |a1|
			adviceListAux -= [a1]
			adviceListAux.each { |a2|
				if @pointcutHash[@adviceHash[a1].pointcut].crash?(@pointcutHash[@adviceHash[a2].pointcut], fin)
					raise 'several pointcuts are crashing'
				end #if
			} #adviceListAux.each 
		} #adviceList.each 
		generationHash.each { |k, g|
			raise "There is another generation with the same output file" if (fout == g.fout) and (name != g.name)
		} #generationHash.each
	 	@generationHash[name] = 
			Generation.new(name, fin, fout, adviceList)		 
	 end #generation

	# Executes all Generations of 'self'
	def generate()
		@generationHash.each_value { |g|
			File.open(g.fin) {|fin|
				stereotypeCode = fin.read
				g.adviceList.each {|adviceKey|
					if @pointcutHash[@adviceHash[adviceKey].pointcut].scope == 'global'
						stereotypeCode.gsub!(@pointcutHash[@adviceHash[adviceKey].pointcut], 
						                              @adviceHash[adviceKey].subText)
						
					else
						stereotypeCode.sub!(@pointcutHash[@adviceHash[adviceKey].pointcut], 
						                             @adviceHash[adviceKey].subText)
					end #if
				} #g.adviceList.each	
				File.open(g.fout, "w+") {|fout|
					fout.write(stereotypeCode)
				} #File.open(g.fout, "w+")				
			} #File.open(g.fin)
		} #@generationHash.each
	end #generate
	
	# Combines two AspectGen objects ('self' and 'aspectGen'). It can raise exceptions when:
	# * Several Generations have the same output file but different stereotype files.
	# * Several Generations have Pointcuts wich overlap ("crash")
	def +(aspectGen)
		raise "Argument of AspectGen#+ must be a AspectGen" if !aspectGen.kind_of?(AspectGen)
		a1 = self.cloneSuffix
		a2 = aspectGen.cloneSuffix
		a1.generationHash.each { |k1, g1|
			a2.generationHash.each { |k2, g2|
				if g1.fout == g2.fout
					File.open(g1.fin) {|fin1|
						stereotypeCode1 = fin1.read
						File.open(g2.fin) {|fin2|
							stereotypeCode2 = fin2.read
							if stereotypeCode1 != stereotypeCode2
								raise "Two generations with the same 'generation file' but different 'stereotype files'"
							else
								g1.adviceList.each {|ad1|
									g2.adviceList.each {|ad2|
										if a1.pointcutHash[a1.adviceHash[ad1].pointcut].crash?(
										   a2.pointcutHash[a2.adviceHash[ad2].pointcut], g1.fin)
											raise 'several pointcuts are crashing'
										end #if
									} #g2.adviceList
								} #g1.adviceList
								g1.adviceList += g2.adviceList
								a2.generationHash.delete(k2)						
							end #if
						} #File.open(g2.fin)
					} #File.open(g1.fin) 
				end #if
			} #a2.generationHash.each
		} #a1.generationHash.each
		a1.generationHash.update(a2.generationHash)	
		a1.adviceHash.update(a2.adviceHash)	
		a1.pointcutHash.update(a2.pointcutHash)	
		return a1
	end #+
	
	def AspectGen.init(*ids)
		# Falta gestion de errores
		for id in ids
			id_value = eval(id.id2name, @args)
			eval "@#{id.id2name} = id_value" 
		end #for
		yield if block_given? 
	end #interface
	
end #AspectGen




 