"""SCons.Tool.JavaCommonStuff for processing Java."""## __COPYRIGHT__## Permission is hereby granted, free of charge, to any person obtaining# a copy of this software and associated documentation files (the# "Software"), to deal in the Software without restriction, including# without limitation the rights to use, copy, modify, merge, publish,# distribute, sublicense, and/or sell copies of the Software, and to# permit persons to whom the Software is furnished to do so, subject to# the following conditions:## The above copyright notice and this permission notice shall be included# in all copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.#__revision__="__FILE__ __REVISION__ __DATE__ __DEVELOPER__"importosimportos.pathimportrejava_parsing=1default_java_version='1.4'ifjava_parsing:# Parse Java files for class names.## This is a really cool parser from Charles Crain# that finds appropriate class names in Java source.# A regular expression that will find, in a java file:# newlines;# double-backslashes;# a single-line comment "//";# single or double quotes preceeded by a backslash;# single quotes, double quotes, open or close braces, semi-colons,# periods, open or close parentheses;# floating-point numbers;# any alphanumeric token (keyword, class name, specifier);# any alphanumeric token surrounded by angle brackets (generics);# the multi-line comment begin and end tokens /* and */;# array declarations "[]"._reToken=re.compile(r'(\n|\\\\|//|\\[\'"]|[\'"\{\}\;\.\(\)]|'+r'\d*\.\d*|[A-Za-z_][\w\$\.]*|<[A-Za-z_]\w+>|'+r'/\*|\*/|\[\])')classOuterState(object):"""The initial state for parsing a Java file for classes, interfaces, and anonymous inner classes."""def__init__(self,version=default_java_version):ifnotversionin('1.1','1.2','1.3','1.4','1.5','1.6','1.7','5','6'):msg="Java version %s not supported"%versionraiseNotImplementedError(msg)self.version=versionself.listClasses=[]self.listOutputs=[]self.stackBrackets=[]self.brackets=0self.nextAnon=1self.localClasses=[]self.stackAnonClassBrackets=[]self.anonStacksStack=[[0]]self.package=Nonedeftrace(self):passdef__getClassState(self):try:returnself.classStateexceptAttributeError:ret=ClassState(self)self.classState=retreturnretdef__getPackageState(self):try:returnself.packageStateexceptAttributeError:ret=PackageState(self)self.packageState=retreturnretdef__getAnonClassState(self):try:returnself.anonStateexceptAttributeError:self.outer_state=selfret=SkipState(1,AnonClassState(self))self.anonState=retreturnretdef__getSkipState(self):try:returnself.skipStateexceptAttributeError:ret=SkipState(1,self)self.skipState=retreturnretdef__getAnonStack(self):returnself.anonStacksStack[-1]defopenBracket(self):self.brackets=self.brackets+1defcloseBracket(self):self.brackets=self.brackets-1iflen(self.stackBrackets)and \
self.brackets==self.stackBrackets[-1]:self.listOutputs.append('$'.join(self.listClasses))self.localClasses.pop()self.listClasses.pop()self.anonStacksStack.pop()self.stackBrackets.pop()iflen(self.stackAnonClassBrackets)and \
self.brackets==self.stackAnonClassBrackets[-1]:self.__getAnonStack().pop()self.stackAnonClassBrackets.pop()defparseToken(self,token):iftoken[:2]=='//':returnIgnoreState('\n',self)eliftoken=='/*':returnIgnoreState('*/',self)eliftoken=='{':self.openBracket()eliftoken=='}':self.closeBracket()eliftokenin['"',"'"]:returnIgnoreState(token,self)eliftoken=="new":# anonymous inner classiflen(self.listClasses)>0:returnself.__getAnonClassState()returnself.__getSkipState()# Skip the class nameeliftokenin['class','interface','enum']:iflen(self.listClasses)==0:self.nextAnon=1self.stackBrackets.append(self.brackets)returnself.__getClassState()eliftoken=='package':returnself.__getPackageState()eliftoken=='.':# Skip the attribute, it might be named "class", in which# case we don't want to treat the following token as# an inner class name...returnself.__getSkipState()returnselfdefaddAnonClass(self):"""Add an anonymous inner class"""ifself.versionin('1.1','1.2','1.3','1.4'):clazz=self.listClasses[0]self.listOutputs.append('%s$%d'%(clazz,self.nextAnon))elifself.versionin('1.5','1.6','1.7','5','6'):self.stackAnonClassBrackets.append(self.brackets)className=[]className.extend(self.listClasses)self.__getAnonStack()[-1]=self.__getAnonStack()[-1]+1foranoninself.__getAnonStack():className.append(str(anon))self.listOutputs.append('$'.join(className))self.nextAnon=self.nextAnon+1self.__getAnonStack().append(0)defsetPackage(self,package):self.package=packageclassAnonClassState(object):"""A state that looks for anonymous inner classes."""def__init__(self,old_state):# outer_state is always an instance of OuterStateself.outer_state=old_state.outer_stateself.old_state=old_stateself.brace_level=0defparseToken(self,token):# This is an anonymous class if and only if the next# non-whitespace token is a bracket. Everything between# braces should be parsed as normal java code.iftoken[:2]=='//':returnIgnoreState('\n',self)eliftoken=='/*':returnIgnoreState('*/',self)eliftoken=='\n':returnselfeliftoken[0]=='<'andtoken[-1]=='>':returnselfeliftoken=='(':self.brace_level=self.brace_level+1returnselfifself.brace_level>0:iftoken=='new':# look further for anonymous inner classreturnSkipState(1,AnonClassState(self))eliftokenin['"',"'"]:returnIgnoreState(token,self)eliftoken==')':self.brace_level=self.brace_level-1returnselfiftoken=='{':self.outer_state.addAnonClass()returnself.old_state.parseToken(token)classSkipState(object):"""A state that will skip a specified number of tokens before reverting to the previous state."""def__init__(self,tokens_to_skip,old_state):self.tokens_to_skip=tokens_to_skipself.old_state=old_statedefparseToken(self,token):self.tokens_to_skip=self.tokens_to_skip-1ifself.tokens_to_skip<1:returnself.old_statereturnselfclassClassState(object):"""A state we go into when we hit a class or interface keyword."""def__init__(self,outer_state):# outer_state is always an instance of OuterStateself.outer_state=outer_statedefparseToken(self,token):# the next non-whitespace token should be the name of the classiftoken=='\n':returnself# If that's an inner class which is declared in a method, it# requires an index prepended to the class-name, e.g.# 'Foo$1Inner' (Tigris Issue 2087)ifself.outer_state.localClassesand \
self.outer_state.stackBrackets[-1]> \
self.outer_state.stackBrackets[-2]+1:locals=self.outer_state.localClasses[-1]try:idx=locals[token]locals[token]=locals[token]+1exceptKeyError:locals[token]=1token=str(locals[token])+tokenself.outer_state.localClasses.append({})self.outer_state.listClasses.append(token)self.outer_state.anonStacksStack.append([0])returnself.outer_stateclassIgnoreState(object):"""A state that will ignore all tokens until it gets to a specified token."""def__init__(self,ignore_until,old_state):self.ignore_until=ignore_untilself.old_state=old_statedefparseToken(self,token):ifself.ignore_until==token:returnself.old_statereturnselfclassPackageState(object):"""The state we enter when we encounter the package keyword. We assume the next token will be the package name."""def__init__(self,outer_state):# outer_state is always an instance of OuterStateself.outer_state=outer_statedefparseToken(self,token):self.outer_state.setPackage(token)returnself.outer_statedefparse_java_file(fn,version=default_java_version):returnparse_java(open(fn,'r').read(),version)defparse_java(contents,version=default_java_version,trace=None):"""Parse a .java file and return a double of package directory, plus a list of .class files that compiling that .java file will produce"""package=Noneinitial=OuterState(version)currstate=initialfortokenin_reToken.findall(contents):# The regex produces a bunch of groups, but only one will# have anything in it.currstate=currstate.parseToken(token)iftrace:trace(token,currstate)ifinitial.package:package=initial.package.replace('.',os.sep)return(package,initial.listOutputs)else:# Don't actually parse Java files for class names.## We might make this a configurable option in the future if# Java-file parsing takes too long (although it shouldn't relative# to how long the Java compiler itself seems to take...).defparse_java_file(fn):""" "Parse" a .java file. This actually just splits the file name, so the assumption here is that the file name matches the public class name, and that the path to the file is the same as the package name. """returnos.path.split(file)# Local Variables:# tab-width:4# indent-tabs-mode:nil# End:# vim: set expandtab tabstop=4 shiftwidth=4: